如何用data.table替换聚合?

时间:2015-11-18 13:18:34

标签: r data.table aggregate

我有以下数据:

> dput(bla)
structure(list(V1 = structure(c(4L, 4L, 4L, 2L), .Label = c("DDDD", 
"EEEE", "NNNN", "PPPP", "ZZZZ"), class = "factor"), V2 = c(100014096L, 
100014098L, 100014099L, 100014995L), V3 = c(0.742, 0.779, 0.744, 
0.42), V4 = c(1.077, 1.054, 1.049, 0.984), V5 = c(0.662, 0.663, 
0.671, 0.487), V6 = c(1.107, 1.14, 1.11, 0.849), V7 = c(0.456, 
0.459, 0.459, 1.278)), .Names = c("V1", "V2", "V3", "V4", "V5", 
"V6", "V7"), class = "data.frame", row.names = c(NA, 4L))

> bla
    V1        V2    V3    V4    V5    V6    V7
1 PPPP 100014096 0.742 1.077 0.662 1.107 0.456
2 PPPP 100014098 0.779 1.054 0.663 1.140 0.459
3 PPPP 100014099 0.744 1.049 0.671 1.110 0.459
4 EEEE 100014995 0.420 0.984 0.487 0.849 1.278

我想执行一个函数来实现以下功能,目前我正在使用aggregate

> linem<- aggregate(bla[,3:7], list(line=bla$V1),mean, na.rm=T) 
> linem
  line    V3    V4        V5    V6    V7
1 EEEE 0.420 0.984 0.4870000 0.849 1.278
2 PPPP 0.755 1.060 0.6653333 1.119 0.458

为了提高这个脚本的性能,我一直在努力掌握data.table来做到这一点。 如何使用data.table获取上述输出?
我一直在尝试使用data.table,但是如果像this question这样的方法更快,它也会很好。

2 个答案:

答案 0 :(得分:7)

我们转换了&#39; data.frame&#39;到&#39; data.table&#39; (setDT(bla)),按&#39; V1&#39;分组,指定.SDcols中的列,循环显示列(lapply(.SD,)并获取mean

 library(data.table)
 setDT(bla)[, lapply(.SD, mean), by = V1, .SDcols= 3:ncol(bla)]
 #     V1    V3    V4        V5    V6    V7
 #1: PPPP 0.755 1.060 0.6653333 1.119 0.458
 #2: EEEE 0.420 0.984 0.4870000 0.849 1.278

答案 1 :(得分:3)

lapply上没有colMeans.SD的“矢量化”选项:

library(data.table)

setDT(bla)[,as.list(colMeans(.SD[,2:6, with=F])), V1]
#     V1    V3    V4        V5    V6    V7
#1: PPPP 0.755 1.060 0.6653333 1.119 0.458
#2: EEEE 0.420 0.984 0.4870000 0.849 1.278