通过引用列名在data.table中进行聚合

时间:2016-10-10 08:50:42

标签: r data.table aggregate

我想通过data.table中列的列表汇总一些列。但是,我想避免使用引号之外的列名(在by = .(desiredColumn1, desiredColumn2)中)。我很高兴使用列名或列索引。例如:

library(data.table)
x = as.data.table(iris)
x[, sum(Sepal.Width), by = .(Sepal.Length, Species)] # I want to avoid doing this
x[, sum("Sepal.Width"), by = .("Sepal.Length", "Species"), with = FALSE] # this does not work
x[, sum("Sepal.Width"), by = .(1, 5), with = FALSE]

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

我们可以将cnames

一起使用
x[, sum(Sepal.Width), by = c(names(x)[c(1, 5)])]