我想按组汇总数据框。要分组的列在不同的编译中动态定义。这里有一个例子。
gender = c(rep(1, 50), rep(2, 50))
weight = round(rnorm(100, 60, 5), 0)
age = floor(runif(100, min=18, max=30))
my_df <- data.frame(gender, age, weight)
result <- function(
df = my_df,
group_by_gender = TRUE,
group_by_weight = TRUE,
group_by_age = TRUE
){
the_result <- df %>%
group_by(
gender, #if(group_by_gender, gender, NULL),
weight, #if(group_by_weight, weight, NULL),
age #if(group_by_age, age, NULL)
) %>%
summarize(
count = n()
)
return(the_result)
}
根据 group_by_* 我想打开或关闭无,一列或多列作为分组依据。我没有看到,如何在 group_by(string) 中构造字符串
最佳答案
您可以创建一个 rlang::expr
对象的向量,然后将其子集化为您想要使用的值,并使用 将其扩展到
。例如group_by
>!!!
result <- function(
df = my_df,
group_by_gender = TRUE,
group_by_weight = TRUE,
group_by_age = TRUE
){
gcols <- rlang::exprs(gender, weight, age)
gkeep <- c(group_by_gender, group_by_weight, group_by_age)
the_result <- df %>%
group_by(!!!gcols[gkeep]) %>%
summarize(
count = n()
)
return(the_result)
}
关于r - 如何创建动态 group_by 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67119039/