在自定义函数-R中使用分组集



我在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"))
)

输出:

>γ_total9>8[/tr>6[/tr>
region_name类型β_total
西部NA15
东部NA96
West小型74
西部big5
东部9

groupingsets来自data.table。因此,它可能不适用于卷曲-卷曲运算符({{}}(。一个选项是创建一个表达式,然后evalutate`

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

相关内容

  • 没有找到相关文章

最新更新