I have a tibble with two string columns that contain names of variables of a data.frame (in this example, iris).
I want to pass that names to a function so that I get a list-column with the results. I don't know how to pass the names to the function mean_group.
suppressMessages(library(dplyr))
df_var <- tibble(group_var = c("Species", "Species"),
var = c("Sepal.Length", "Sepal.Width"))
mean_group <- function(data, group_var, mean_var) {
data %>%
group_by({{ group_var }}) %>%
summarise(mean = mean({{ mean_var }}))
}
# Using dplyr, naive approach
df_var %>%
mutate(tab = list(mean_group(iris, group_var, var)))
#> Error: Column `group_var` is unknown
# Using purrr
df_var %>%
mutate(tab = purrr::map2(group_var, var, ~mean_group(iris, .x, .y)))
#> Error: Column `.x` is unknown
# Expected result:
# This is what I expect to get inside a list-column.
t1 <- mean_group(iris, Species, Sepal.Length)
t2 <- mean_group(iris, Species, Sepal.Width)
df_var <- df_var %>%
mutate(tab = list(t1, t2))
df_var
#> # A tibble: 2 x 3
#> group_var var tab
#> <chr> <chr> <list>
#> 1 Species Sepal.Length <tibble [3 × 2]>
#> 2 Species Sepal.Width <tibble [3 × 2]>
# After that, I'll do this:
df_var %>%
tidyr::unnest_longer(tab)
#> # A tibble: 6 x 3
#> group_var var tab$Species $mean
#> <chr> <chr> <fct> <dbl>
#> 1 Species Sepal.Length setosa 5.01
#> 2 Species Sepal.Length versicolor 5.94
#> 3 Species Sepal.Length virginica 6.59
#> 4 Species Sepal.Width setosa 3.43
#> 5 Species Sepal.Width versicolor 2.77
#> 6 Species Sepal.Width virginica 2.97
Created on 2020-02-04 by the reprex package (v0.3.0)