聚合时将列名称动态添加到data

聚合时将列名称动态添加到data

本文介绍了聚合时将列名称动态添加到data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在通过引用创建列时(使用:= ),我们可以动态添加列名,例如此处:。

I know we can dynamically add column names when creating columns by reference (using :=), as described e.g. here: Dynamic column names in data.table.

但是,我希望在聚合时动态添加列名。您可以帮忙吗?

However, I'm looking to dynamically add column names when we aggregate. Can you help with this?

test_dtb <- data.table(a = sample(1:100, 100), b = sample(1:100, 100), id = rep(1:10, 10))
m = "blah"
test_dtb[ , list((m) = mean(b)), by = id]

我得到的错误是

Error: unexpected '=' in "test_dtb[ , list((m) =


推荐答案

如lukeA的注释中所述,可以使用 setNames :

As mentioned in the comments by lukeA, setNames can be used:

m <- c("blah", "foo")
test_dtb[ , setNames(list(mean(b), median(b)), m), by = id]

这篇关于聚合时将列名称动态添加到data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:09