【问题标题】:How to create dynamic group_by parameters如何创建动态 group_by 参数
【发布时间】:2021-07-11 02:45:07
【问题描述】:

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


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) 中构造字符串

【问题讨论】:

    标签: r dplyr group-by


    【解决方案1】:

    您可以创建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)
    }
    

    【讨论】:

    • 我只是想了解!!!gcols[gkeep] 在这里是如何工作的?你能在答案中解释一下吗?
    • 这在rlang 准引用参考:rlang.r-lib.org/reference/quasiquotation.html 或高级 R 指南:adv-r.hadley.nz/quasiquotation.html 中有介绍
    • 如果使用出生日期而不是年龄并且使用函数确定年龄,则此解决方案也有效。 gcols &lt;- rlang::exprs(gender, weight, year = year(birthdate))
    【解决方案2】:

    您可以在group_by 函数中调用.dots 参数:

    result <- function(df = my_df, group_by_gender = TRUE, 
                       group_by_weight = TRUE, group_by_age = TRUE){
      nms <- c("gender","weight", "age")
      bool <- c(group_by_gender, group_by_weight, group_by_age)
      
      the_result <- df %>%
        group_by(.dots = nms[bool]) %>%
        summarize(count = n(), .groups = "keep")
      return(the_result)
    }
    

    【讨论】:

    猜你喜欢
    • 2011-01-14
    • 2021-02-27
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2011-07-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多