使用R中的for循环中的变量传递data.table中的列名

时间:2016-11-17 14:38:11

标签: r for-loop data.table

我想循环遍历数据表中的一系列列,并按该列汇总我的数据。我可以使用quote()eval()将列名称作为变量传递,并且工作正常

library("data.table")

dt <- data.table(x=c("b","b","b","a","a","c","c"), y = c("x","y","z","x","y","z","x"), v=rnorm(7))

splitBy <- quote(y)

sdt <- dt[,list(meanV = mean(v)),by=. (eval(splitBy))]

然而,当我尝试将其放入像这样的循环中时

library("data.table")

dt <- data.table(x=c("b","b","b","a","a","c","c"), y = c("x","y","z","x","y","z","x"), v=rnorm(7))

myList <- c("x","y")

for (i in myList){

  splitBy <- quote(i)
  sdt <- dt[,list(meanV = mean(v)),by=. (eval(splitBy))]

}

它不起作用。我知道split by正确评估为xy。我做错了什么?

0 个答案:

没有答案