An R function with a parameter that accepts a data.frame column can’t evaluate the column argument until it is first ‘quoted’, followed by an ‘unquote’ within the dyplr
function.
‘Quote’ a column using enquo()
, then ‘unquote’ it using !!
.
Try it
library(dplyr)
# build example data.frame
id <-c(1,2,3,4,5,6)
value <- c('a','b','b','c','c','c')
df <- data.frame(id, value)
# create function to count data.frame column values
my_function <- function(data, col) {
col <- enquo(col) # quote
data %>%
group_by(!!col) %>% # unquote
summarise(count = n())
}
# call function, passing data.frame and column
my_function(df, value)
# A tibble: 3 x 2
value count
<fct> <int>
1 a 1
2 b 2
3 c 3
Of course, you could enquo()
the column as it’s passed to the function. Personally, I like to keep function calls cleaner by performing function-required manipulations on arguments within the function itself.
my_function <- function(data, col) {
data %>%
group_by(!!col) %>% # unquote
summarise(count = n())
}
# call function with column 'quoted'
my_function(df, enquo(value)) # quote
# A tibble: 3 x 2
value count
<fct> <int>
1 a 1
2 b 2
3 c 3
What if we want to pass an expression, e.g. year(survey_date)?