【问题标题】:Aggregation in data.table by reference to column names [duplicate]通过引用列名在data.table中进行聚合[重复]
【发布时间】:2016-10-10 08:50:41
【问题描述】:

我想通过 data.table 中的 list 列来聚合一些列。但是,我想避免使用引号之外的列名(即在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]

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

【问题讨论】:

    标签: r data.table aggregate


    【解决方案1】:

    我们可以使用cnames

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

    【讨论】:

    • 您好 akrun,谢谢您的回答。我怎样才能避免提及Sepal.Length?例如:x[, sum("Sepal.Length"), by = c(names(x)[c(1, 5)]), with = FALSE] # this fails
    • @GerasimosPanagiotakopoulos 你不是直接指Sepal.Length。你是说Sepal.Width
    • 是的,你是对的。我的意思是Sepal.Width
    • @GerasimosPanagiotakopoulos 您可以在.SDcols 中指定它或使用getevalx[, sum(get(names(x)[2])), by = c(names(x)[c(1, 5)])]
    • 不需要names(x)。这有效:x[, sum(get("Sepal.Width")), by = c("Sepal.Length", "Species")]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2013-11-19
    • 2014-04-28
    • 2019-09-09
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多