我想循环遍历数据表中的一系列列,并按该列汇总我的数据。我可以使用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正确评估为x
或y
。我做错了什么?