我有一个很大的数据集,我想根据它们的位置互相减去特定的列。我想从第8列减去第2列,从第9列减去第3列,并从第10列减去第4列。
非常感谢
马格努斯
mailchimp/marketing/lib/Configuration.php
答案 0 :(得分:3)
我们可以创建2个位置向量,并直接减去各列。由于您拥有data.table
,因此我们使用..column_number
按位置选择列。
library(data.table)
col1group <- 2:4
col2group <- 8:10
df[, ..col1group] - df[, ..col2group])
如果要将它们作为新列添加到原始数据中,可以重命名它们,并cbind
cbind(df, setNames(df[, ..col1group] - df[, ..col2group],
paste0(names(df)[col1group], '_diff')))
答案 1 :(得分:1)
类似于以下内容的方法计算问题中的减法。
library(data.table)
nms <- names(df1)
iCols <- grep("^i\\.", nms, value = TRUE)
Cols <- sub("^i\\.", "", iCols)
df1[, lapply(seq_along(Cols), function(i) get(Cols[i]) - get(iCols[i]))]
# V1 V2 V3
#1: -0.0061970 0.0156564 -1.64872
#2: -0.0765590 0.0100962 0.45382
#3: -0.3198350 -0.0715609 -14.29002
#4: -0.0471500 -0.0570996 -3.01273
#5: 0.0655143 -0.0113157 1.82301
#6: -0.5673930 -0.1427161 -19.09679
在回答Ronak Shah's之后,我意识到下面的代码也有效。
df1[, ..Cols] - df1[, ..iCols]
数值结果相同,但列名称为向量Cols
。
要创建新列,请尝试
newCols <- paste(Cols, "diff", sep = "_")
df1[, (newCols) := lapply(seq_along(Cols), function(i) get(Cols[i]) - get(iCols[i]))]
答案 2 :(得分:1)
Base R解决方案:
idx <- c(2, 3, 4)
jdx <- c(8, 9, 10)
使用lapply()
和列绑定列表:
setNames(do.call("cbind", lapply(seq_along(idx), function(i){
df[, jdx[i], drop = FALSE] - df[, idx[i], drop = FALSE]
}
)
), c(paste("x", jdx, idx, sep = "_")))
使用sapply()
并将矢量强制转换为data.frame:
setNames(data.frame(sapply(seq_along(idx), function(i){
df[, jdx[i], drop = FALSE] - df[, idx[i], drop = FALSE]
}
)
), c(paste("x", jdx, idx, sep = "_")))
使用Map()
和Reduce()
并将列绑定到原始数据。frame:
cbind(df, setNames(Reduce(cbind, Map(function(i){
df[, jdx[i], drop = FALSE] - df[, idx[i], drop = FALSE]
}, seq_along(idx))), c(paste("x", jdx, idx, sep = "_"))))