take mean of variable defined by string in dplyr

Viewed 631

Seems like this should be easy but I'm stumped. I've gotten the rough hang of programming with dplyr 0.7, but struggling with this: How do I program in dplyr if the variable I want to program with will be a string?

I am scraping a database, and for a variety of reasons want to summarize a variable that I will know the position of but not the name of (the thing I want is always the first column of the supplied table, but the name of the variable stored in that column will vary depending on the database being scraped). To use iris as an example, suppose that I know that the variable that I want is in the first column

library(tidyverse)
desired_var <- colnames(iris)[1]
print(desired_var)
"Sepal.Length"

I now want to group by Species, and take the mean of desired_var, i.e. what I want is to perform

iris %>% 
group_by(Species) %>% 
summarise(desired_mean = mean(Sepal.Length))

But, now I want to take the mean of a column which is defined by a string stored in desired_var

I get how to do this with a "bare" Sepal.Length

desired_var <- quo(Sepal.Length)

iris %>% 
group_by(Species) %>% 
summarise(desired_mean = mean(!!desired_var))

But how in the world do I deal with the fact that I have "Sepal.Length" not Sepal.Length , i.e. that desired_var <- "Sepal.Length" ?

2 Answers
Related