'How to refer to column names using a vector in R map / dplyr

I'd like to refer to a column name in a data frame using the quoted (string) version of the column name when I call a function. This is because I want to map the function through various character vectors that contain column names. (I can't simply map through the data frame itself because of other reasons.)

This works:

library(tidyverse)
head(iris)

summariseByGroup = function(dat, grouping_var, column_name){
  dat %>%
    group_by({{grouping_var}}) %>%  
    summarise(sum = sum({{column_name}}))
}

summariseByGroup(iris, Species, Sepal.Length)

>  Species      sum
  <fct>      <dbl>
1 setosa      250.
2 versicolor  297.
3 virginica   329.

This doesn't work:

summariseByGroup(iris, Species, 'Sepal.Length')

Error in `summarise()`:
! Problem while computing `sum = sum("Sepal.Length")`.
ℹ The error occurred in group 1: Species = setosa.
Caused by error in `sum()`:
! invalid 'type' (character) of argument

This is because of some aspect of evaluation that I can't wrap my head around.

Is there a workaround that unqoutes the string and evaluates it as a column name?



Solution 1:[1]

Following @Zoe's pointer to Pass a string as variable name in dplyr::filter

summariseByGroup2 = function(dat, grouping_var, column_name){
  dat %>%
    group_by({{grouping_var}}) %>%  
    summarise(sum = sum(get(column_name)))
}

summariseByGroup2(iris, Species, 'Sepal.Length')

# A tibble: 3 × 2
  Species      sum
  <fct>      <dbl>
1 setosa      250.
2 versicolor  297.
3 virginica   329.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 petyar