This is the type of thing I do all the time in R. I know that there's an easier way to do this using map_df.
For the life of me, I can't figure out how to do this using purrr.
I want to feed the function a vector of variable names. In this case: drat, wt, qsec.
Then, I want to add a column that I am calling "name" here: Rear Axle Ratio, Weight, Quarter Mile Time.
That way I can use the name column to facet when I get to ggplot.
calc <- function(df, var, type){
df %>%
group_by(cyl) %>%
summarise(mean = mean({{var}})) %>%
mutate(name = type)
}
yyy1 <- mtcars %>% calc(drat, "Rear Axle Ratio")
yyy2 <- mtcars %>% calc(wt, "Weight")
yyy3 <- mtcars %>% calc(qsec, "Quarter Mile Time")
graph <- bind_rows(yyy1, yyy2, yyy3)
graph
I want to do something like:
calc <- function(df, var, type){
df %>%
group_by(cyl) %>%
summarise(mean = mean({{var}})) %>%
mutate(name = type)
}
vars <- c(drat, wt, qsec)
names <- c("Rear Axle Ratio", "Weight", "Quarter Mile Time")
all <- map_df(vars, names, calc)
But I can't figure out how to pass a column name into the function.