I have a function that calculates the means of a grouped database for a column which is chosen based on the content of a variable VarName
. The current function uses dplyr::summarize_
, but now I see this is deprecated, and I want to replace it before it is fully removed.
However, I'm not sure how to use the new unquoting to achieve what I'm trying to do. Here's my current code:
means<-summarize_(group_by(dat,Grade),.dots = setNames(paste0('mean(',VarName,',na.rm=TRUE)'),'means'))
I tried replacing the .dots
part with means=mean(!!VarName, na.rm=TRUE)
, but that just returned the string inside VarName. What I need is for the string in VarName to be evaluated as the column name within dat
, so that I'll get a column name "means" with the mean of each group. How can I achieve that with the new summarize
?
Sample dataset for reproducibility:
VarName<-"Things"
dat<-data.frame(students=c("a","b","c","d","e"),Grade=c(2,2,2,3,3),varA=c(41:45),Things=c(90,100,80,75,80))
Thanks!