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?