我在R中工作,我有以下数据:
data2<- data.frame(region_name = c("West", "West", "East"),
type = c("small", "big", "big"),
beta_rate = 7:9,
gamma_rate = 4:6)
我对它进行分组以聚合总数:
data_i_want <- data2 %>%
as.data.table() %>% groupingsets(
j = .(
beta_total = sum(beta_rate),
gamma_total = sum(gamma_rate)),
by = c("region_name","type"),
sets = list(
c("region_name"),
c("region_name","type"))
)
输出:
region_name | 类型 | β_total | >γ_total|
---|---|---|---|
西部 | NA | 15 | 9|
东部 | NA | 9 | 6 |
West | 小型 | 7 | >4 |
西部 | big | 85 | [/tr>|
东部 | 大 | 9 | 6[/tr>
groupingsets
来自data.table
。因此,它可能不适用于卷曲-卷曲运算符({{}}
(。一个选项是创建一个表达式,然后eval
utate`
my_function <- function(data, var1, var2) {
var1 <- deparse(substitute(var1))
var2 <- deparse(substitute(var2))
eval(parse(text = glue::glue("data %>%
as.data.table() %>%
groupingsets(
j = .(
beta_total = sum({var1}),
gamma_total = sum({var2})),
by = c('region_name','type'),
sets = list(
c('region_name'),
c('region_name','type'))
)")))
}
-测试
my_function(data2, beta_rate, gamma_rate)
region_name type beta_total gamma_total
<char> <char> <int> <int>
1: West <NA> 15 9
2: East <NA> 9 6
3: West small 7 4
4: West big 8 5
5: East big 9 6