R:for data with data.table库

时间:2014-09-19 21:45:34

标签: r data.table

我正在使用library(data.table),我希望根据for值执行mean循环计算1:4col5。< / p>

colnames(DT) # "col1" "col2" "col3" "col4" "col5" 
for (i in 1:4){
  o=colnames(DT)[[i]]
  l=DT[,mean(o), by=col5]
  print(l)
}

问题是DT不会将colnames作为character向量(&#34; col&#34;)。任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:2)

阅读data.table vignettes。

library(data.table)
set.seed(42)
DT <- data.table(matrix(rnorm(100), ncol=4))
setnames(DT, paste0("col", 1:4))
DT[, col5 := rep(1:5, 5)]

DT[, lapply(.SD, mean), by = col5]

DT[, lapply(.SD, mean), by = col5, .SDcols = paste0("col", 2:3)]

答案 1 :(得分:-2)

尝试:

DT[,list(mean1=mean(col1), mean2=mean(col2), mean3=mean(col3), mean4=mean(col4)),by=col5]

如果列太多:

attach(DT)    
for(i in 1:4) print(DT[,mean(get(colnames(DT)[i])),by=DT[,5,with=F]])