我正在尝试聚合data.table。更确切地说,我有一个202列的data.table,我想要aggregate(dt[,131:202]~dt[,1:130],data=dt,FUN=sum)
。
这是一个data.table,所以你可以尝试这样做。
A <- c(1,2,3,4,4,6,4)
B <- c("a","b","c","d","e","f","g")
C <- c(10,11,23,8,8,1,3)
D <- c(2,3,5,9,7,8,4)
E <- c(2,5,7,1,4,6,15)
G <- c("b","f","s","k","t","r","n")
H <- c(2,68,5,27,11,17,4)
dt <- data.table(A,B,C,D,E,G,H)
答案 0 :(得分:4)
data.table选项用于指定.SDcols
中感兴趣的列,对by
中的列进行分组,循环遍历.SD
(data.table的子集)并获取sum
dt[, lapply(.SD, sum), by = c(names(dt)[1:130]), .SDcols = 131:202]
set.seed(24)
d1 <- as.data.frame(matrix(sample(LETTERS[1:7], 130*20, replace = TRUE),
20, 130), stringsAsFactors=FALSE)
d2 <- as.data.frame(matrix(sample(1:20, 130*20, replace = TRUE), 20,
130), stringsAsFactors=FALSE)
dt <- data.table(d1, d2)
names(dt) <- make.unique(names(dt))