Error with using enquo for creating function with ddplyr

后端 未结 1 614
孤独总比滥情好
孤独总比滥情好 2021-01-29 01:18

enter image description here

I have the data above, i want to aggregate some variables on the basis of mean of SalesInThousand Variable.

I am creating a function

相关标签:
1条回答
  • 2021-01-29 01:45

    The function arguments should match the ones inside the function i.e. if the argument of the data is 'df', it should be the same inside the function as well

    testFunction <- function(df , x) {
     x <- enquo(x)
     df %>%
       group_by(!! x) %>%
       summarize(mean.Petal.Width = mean(Petal.Width))
    }
    
    testFunction(iris, Species)
    # A tibble: 3 x 2
    #    Species mean.Petal.Width
    #      <fctr>            <dbl>
    #1     setosa            0.246
    #2 versicolor            1.326
    #3  virginica            2.026
    

    If we need to aggregate multiple variables, then use the summarise_at or summarise_all

    testFunction <- function(df , varS, x) {
     x <- enquo(x)
     df %>%
       group_by(!! x) %>%
       summarize_at(vars(varS), funs(mean = mean(.)))
    }
    
    nm1 <- names(iris)[1:3]
    testFunction(iris, nm1, Species)
    # A tibble: 3 x 4
    #     Species Sepal.Length_mean Sepal.Width_mean Petal.Length_mean
    #      <fctr>             <dbl>            <dbl>             <dbl>
    #1     setosa             5.006            3.428             1.462
    #2 versicolor             5.936            2.770             4.260
    #3  virginica             6.588            2.974             5.552
    
    0 讨论(0)
提交回复
热议问题