Search code examples
rdplyrnon-standard-evaluation

Non-standard evaluation, R, dplyr


The output below is close to what I want, but not quite. Rather than label being equal to the value of var (e.g. Setosa) I want it to be equal to the name of var (i.e. Species). Seems like a silly thing to do, but hey, it is a reprex.

  library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
grouped_mean_and_label <- function(var){
  iris%>%
    group_by({{  var  }})%>%
    summarize(Sepal.Length = mean(Sepal.Length))%>%
    mutate(grouped_by = {{  var  }})
}
grouped_mean_and_label(Species)
#> # A tibble: 3 × 3
#>   Species    Sepal.Length grouped_by
#>   <fct>             <dbl> <fct>     
#> 1 setosa             5.01 setosa    
#> 2 versicolor         5.94 versicolor
#> 3 virginica          6.59 virginica

Created on 2022-08-18 by the reprex package (v2.0.1)


Solution

  • You can use rlang::englue too

    grouped_mean_and_label <- function(var){
    
      iris %>%
        group_by({{  var  }})%>%
        summarize(Sepal.Length = mean(Sepal.Length), 
                  grouped_by = rlang::englue("{{var}}"))
    }
    

    Resulting in:

    grouped_mean_and_label(Species)
    #> # A tibble: 3 × 3
    #>   Species    Sepal.Length grouped_by
    #>   <fct>             <dbl> <chr>     
    #> 1 setosa             5.01 Species   
    #> 2 versicolor         5.94 Species   
    #> 3 virginica          6.59 Species
    

    Another rlang option would be as_label(quo(var))