How to use function arguement to set column name

前端 未结 2 1336
执笔经年
执笔经年 2020-12-20 01:14

I have dataframe df as follows:

df <- data.frame(x = c(\"A\", \"A\", \"B\", \"B\"), y = 1:4)

And I have a function that fin

2条回答
  •  星月不相逢
    2020-12-20 01:24

    We can make use of the quosure from the devel version of dplyr (soon to be released 0.6.0)

    generateVarMean <- function(df, x, y) {
       x <- enquo(x)
       y <- enquo(y)
       newName <- paste0(quo_name(y), ".mean")
       df %>%
           select(UQ(x), UQ(y)) %>%
           group_by(UQ(x)) %>%
           summarise(UQ(newName) := mean(UQ(y), na.rm = TRUE))            
     }
    
    generateVarMean(df1, a, b)
    # A tibble: 2 × 2
    #       a b.mean
    #    
    #1      A    1.5
    #2      B    3.5
    

    We get the input arguments as quosure with enquo, convert the quosure to string with quo_name to create 'newName' string. Then, evaluate the quosure inside select/group_by/summarise by unquoting (UQ or !!). Note that in the new version, we can also assign the column names directly and using the assign operator (:=)

提交回复
热议问题