gpt4 book ai didi

r - 当 "by"分组变量存储为字符串向量时汇总 data.table

转载 作者:行者123 更新时间:2023-12-04 09:35:44 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Use a character vector in the `by` argument

(2 个回答)


去年关闭。




我正在尝试将数据表总结为函数的一部分。分组变量根据用户要求/数据而变化。分组变量作为字符串向量输入。如何将其用作分组变量?见下面的代码

library(data.table)
test <- as.data.table(mtcars)

grouping_vars <- c("vs", "am")

#does what I would like
test[,.(counts = .N,
mpg = mean(mpg),
disp = median(disp)), by = .(vs,am)]

#throws error
test[,.(counts = .N,
mpg = mean(mpg),
disp = median(disp)), by = .(grouping_vars)]

#only gets the first variable
test[,.(counts = .N,
mpg = mean(mpg),
disp = median(disp)), by = .(get(grouping_vars))]

最佳答案

而不是 .( ,这里我们可以使用 c(

library(data.table)
test[,.(counts = .N,
mpg = mean(mpg),
disp = median(disp)), by = c(grouping_vars)]
# vs am counts mpg disp
#1: 0 1 6 19.75000 160.0
#2: 1 1 7 28.37143 79.0
#3: 1 0 7 20.74286 167.6
#4: 0 0 12 15.05000 355.0

关于r - 当 "by"分组变量存储为字符串向量时汇总 data.table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62601509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com