【问题标题】:Dynamic column name with group by condition in R [duplicate]R中按条件分组的动态列名[重复]
【发布时间】:2021-06-21 07:43:33
【问题描述】:

我想使用动态输入列名按条件分组。

df:
col1
a
b
c
d
a
c
d
b
a
b
d

我创建了如下函数

fun1 <- function(df,column_name){
  
  col_name1 = noquote(column_name)
  
  out_df = df %>% group_by(col_name1)%>%dplyr::summarise('Count'=n())
                                                              
  return(out_df)
}

where column_name is string. Example: column_name = 'col1'

当应用该函数时,它会给出以下错误:

Error: Must group by variables found in `.data`.
* Column `col_name1` is not found.

即使存在列,我也会遇到错误。我哪里出错了?

【问题讨论】:

    标签: r dplyr group-by


    【解决方案1】:
    library(dplyr)
    fun1 <- function(df,column_name){
      
      col_name1 <-  sym(column_name)
      
      out_df <-  df %>% 
        group_by(!!col_name1) %>%
        summarise('Count' = n())
      
      return(out_df)
    }
    
    fun1(iris, "Species")
    
    # A tibble: 3 x 2
      Species    Count
      <fct>      <int>
    1 setosa        50
    2 versicolor    50
    3 virginica     50
    

    这也应该有效,优点是能够使用多个字符串:

    fun1 <- function(df, column_name){
      df %>% 
        group_by(across(one_of(column_name))) %>%
        summarise('Count' = n())
      
    }
    

    【讨论】:

    • 嗨,我遇到了同样的错误。
    • fun1(iris, "Species") 这对我有用
    • 是的,现在可以了。你可以解释吗 !!列名之前的这个运算符?
    • 调用sym函数引用字符串,!!告诉函数使用引用文本(即col_name1的值)而不是变量本身。很好的解释在这里dplyr.tidyverse.org/articles/programming.html
    【解决方案2】:

    你可以使用.data代词-

    fun1 <- function(df,column_name){
    
      out_df = df %>% group_by(.data[[column_name]]) %>% summarise(Count = n())
      return(out_df)
    }
    
    fun1(df, 'col1')
    
    #  col1  Count
    #  <chr> <int>
    #1 a         3
    #2 b         3
    #3 c         2
    #4 d         3 
    

    这也可以用count 编写,其工作方式相同 -

    fun2 <- function(df,column_name){
      df %>% count(.data[[column_name]], name = 'Count')
    }
    fun2(df, 'col1')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多