I'm trying to get a custom group_by function working using quosure. It works fine when the input into the function is the name of a field. However, if I want to create a variable that contains the name of the field to insert into the function, I get stuck because the field is quoted. Anyone know how to get around this. Please see below
groupedMean<-function(field){
expr<-enquo(field)
mtcars%>%
group_by(!!expr)%>%
summarise(mean(mpg))
}
#Works
groupedMean(cyl)
#Doesn't work
groupFields<-c("cyl","gear")
for(var in groupFields){
print(groupedMean(eval(var)))
}
One option is to convert it using sym
from rlang
for(var in groupFields){
var <- rlang::sym(var)
print(groupedMean(!!var))
}
# A tibble: 3 x 2
# cyl `mean(mpg)`
# <dbl> <dbl>
#1 4 26.66364
#2 6 19.74286
#3 8 15.10000
# A tibble: 3 x 2
# gear `mean(mpg)`
# <dbl> <dbl>
#1 3 16.10667
#2 4 24.53333
#3 5 21.38000
Instead of print
ing, for later use, the output can be stored in a list
lst <- setNames(vector('list', length(groupFields)), groupFields)
for(var in groupFields){
var <- rlang::sym(var)
lst[[var]] <- groupedMean(!!var)
}
lst