聚合时动态将列名添加到 data.table [英] Dynamically add column names to data.table when aggregating

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

问题描述

我知道我们可以在通过引用创建列时动态添加列名(使用 :=),如所述,例如此处: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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆