r - 如何创建动态 group_by 参数

标签 r dplyr group-by

我想按组汇总数据框。要分组的列在不同的编译中动态定义。这里有一个例子。


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/

相关文章:

node.js - 如何使用 retrhinkdb 获取 json 数据

mysql - 获取项目的最后状态

r - 将 rpois 和 rnbinom 与 dplyr 命令一起使用

r - 规模转化产生的NaN

R ggplot图例在我想要整数时给出小数

r - R 是否具有类似于 Python、C 中的 main 函数的功能?

r - 如何使用 dplyr 选择多个字段

r - 使用 R 中的管道创建 data.frame - 并命名列

MySQL,反转 SELECT GROUP BY

r - R 中使用汇总数据的方差分析