Use ddply within a function and include variable of interest as an argument

前端 未结 4 1150
南方客
南方客 2020-12-30 13:24

I am relatively new to R, and trying to use ddply & summarise from the plyr package. This post almost, but not quite, answers my question. I could use some additional ex

4条回答
  •  猫巷女王i
    2020-12-30 13:26

    With the introduction of quosures in the devel version of dplyr (soon to be released 0.6.0), this becomes a bit more easier

    library(dplyr)
    descriptives_by_groupN <- function(dataset, group, x) {
    
       group <- enquo(group)
       x <- enquo(x)
    
      dataset %>%
             group_by(!!group) %>%
             summarise(Mean = mean(!!x),
                    SD = sd(!!x),
                    Min = min(!!x),
                    Max = max(!!x))
    }
    
    descriptives_by_groupN(mtcars, cyl, hp)
    # A tibble: 3 × 5
    #   cyl      Mean       SD   Min   Max
    #             
    #1     4  82.63636 20.93453    52   113
    #2     6 122.28571 24.26049   105   175
    #3     8 209.21429 50.97689   150   335
    

    Here, the input arguments are converted to quosures with enquo, and inside the group_by/summarise, unquote the quosures (!! or UQ) to get it evaluated

提交回复
热议问题