【问题标题】:How to use "summarise" from dplyr with dynamic column names?如何将 dplyr 中的“摘要”与动态列名一起使用?
【发布时间】:2023-03-07 05:45:01
【问题描述】:

我正在使用 R 中 dplyr 包中的 summarize 函数从表中汇总组均值。我想使用存储在另一个变量中的列名字符串动态地执行此操作。

以下是“正常”的方式,当然可以:

myTibble <- group_by( iris, Species)
summarise( myTibble, avg = mean( Sepal.Length))

# A tibble: 3 x 2
  Species     avg
  <fct>      <dbl>
1 setosa      5.01
2 versicolor  5.94
3 virginica   6.59

但是,我想做这样的事情:

myTibble <- group_by( iris, Species)
colOfInterest <- "Sepal.Length"
summarise( myTibble, avg = mean( colOfInterest))

我已经阅读了Programming with dplyr 页面,并尝试了quoenquo!!.dots=(...) 等的一系列组合,但我还没有弄清楚正确的方法。

我也知道this answer,但是,1) 当我使用标准评估函数standardise_ 时,R 告诉我它已被贬值,并且 2) 答案似乎一点也不优雅。那么,有没有一种好的、简单的方法来做到这一点?

谢谢!

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:

    1) 像这样使用!!sym(...)

    colOfInterest <- "Sepal.Length"
    iris %>% 
      group_by(Species) %>%
      summarize(avg = mean(!!sym(colOfInterest))) %>%
      ungroup
    

    给予:

    # A tibble: 3 x 2
      Species      avg
      <fct>      <dbl>
    1 setosa      5.01
    2 versicolor  5.94
    3 virginica   6.59
    

    2)第二种方法是:

    colOfInterest <- "Sepal.Length"
    iris %>% 
      group_by(Species) %>%
      summarize(avg = mean(.data[[colOfInterest]])) %>%
      ungroup
    

    当然,这在基础 R 中是直截了当的:

    aggregate(list(avg = iris[[colOfInterest]]), iris["Species"], mean)
    

    【讨论】:

      【解决方案2】:

      另一种解决方案:

      iris %>% 
        group_by(Species) %>% 
        summarise_at(vars("Sepal.Length"), mean) %>%
        ungroup()
      
      # A tibble: 3 x 2
        Species    Sepal.Length
        <fct>             <dbl>
      1 setosa             5.01
      2 versicolor         5.94
      3 virginica          6.59
      

      【讨论】:

        猜你喜欢
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 2022-11-22
        • 2021-09-07
        相关资源
        最近更新 更多