Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将数据帧中的所有小数乘以常数?_R - Fatal编程技术网

R 如何将数据帧中的所有小数乘以常数?

R 如何将数据帧中的所有小数乘以常数?,r,R,sapply沿着数字列,使用ifelse将任何元素乘以小数部分,然后cbind原始数据的第一列使用以下内容: > data id V1 V2 V3 1 10001 10 5 1030 2 10002 11 7 11 3 10003 15 21 19 4 10004 930 3020 12 使用模函数%%查找带有小数部分的条目 注意浮点近似错误 cbind(data[1],sapply(data[-1],f

sapply
沿着数字列,使用
ifelse
将任何元素乘以小数部分,然后
cbind
原始数据的第一列使用以下内容:

> data
    id    V1   V2     V3
1 10001   10    5   1030
2 10002   11    7     11
3 10003   15   21     19
4 10004  930 3020     12

使用模函数
%%
查找带有小数部分的条目

注意浮点近似错误

cbind(data[1],sapply(data[-1],function(x) ifelse(x%%1,x*100,x)))
     id  V1   V2   V3
1 10001  10    5 1030
2 10002  11    7   11
3 10003  15   21   19
4 10004 930 3020   12
data.frame(lappy)(数据,函数(x){
如果(是数字(x)){
x[x%%1>0]0]*100
返回(x)
}否则返回(x)
}))
另一种方式:

data.frame(lapply(data, function(x) {
    if(is.numeric(x)) {
        x[x %% 1 > 0] <- x[x %% 1 > 0] * 100
        return(x)
    } else return(x)
}))
d.m这里有一种方法:

d.m <- data.matrix(data)
decs <- as.integer(d.m) != d.m
data[decs] <- d.m[decs] * 100
#      id  V1   V2   V3
# 1 10001  10    5 1030
# 2 10002  11    7   11
# 3 10003  15   21   19
# 4 10004 930 3020   12
>索引数据[,-1][index]数据
id V1 V2 V3
1 10001  10    5 1030
2 10002  11    7   11
3 10003  15   21   19
4 10004 930 3020   12

+1在看到您的答案后,我才知道如何从输入中导出预期输出。如果您事先知道只有
id
列是非十进制的,并且所有其他条目都是“十进制的”,则
数据[,-1]@CarlWitthoft将你的建议与OP发布的预期结果进行核对。@MatthewPlourd说得很对——这不仅让我担心自己,也让我担心这三位投票人:(@CarlWitthoft从好的方面看,也许你有一个粉丝俱乐部。正如我和你的答案同时指出的那样:-),只有当OP的定义中所有的
id
值都是非特定值时,这才起作用。我的变量省略了
id
变量,因此它不会对
id
进行操作,它只对
V1,…,V2
@CarlWitthoft进行操作。假设OP不打算转换id列似乎是安全的。@MatthewPlourd是的,但是你知道关于“假设”的那句老话:-+1对于这个矢量化的解决方案!即使data.matrix是危险的,如果id是一个字符,例如…@agstudy,谢谢。嗯,显然不管第一列的内容是什么,如果它是字符,
data.matrix
将把它转换成连续整数。这就是你所说的危险吗?
d.m <- data.matrix(data)
decs <- as.integer(d.m) != d.m
data[decs] <- d.m[decs] * 100
#      id  V1   V2   V3
# 1 10001  10    5 1030
# 2 10002  11    7   11
# 3 10003  15   21   19
# 4 10004 930 3020   12
> index  <- data[, -1] %% 1 != 0
> data[, -1][index] <- data[, -1][index] *100 
> data
     id  V1   V2   V3
1 10001  10    5 1030
2 10002  11    7   11
3 10003  15   21   19
4 10004 930 3020   12