I've got a function that uses tidyeval to refer to a column name, but also needs to access that column name as a string. The code for that works fine, see below (though improvements welcome, as_name(enquo(x))
seems clunky).
But I can't figure out how to write a wrapper function to use purrr::map()
to maps over multiple columns using this function. Whatever I try either fails entirely or doesn't get the right string value of the column names.
library(dplyr, warn.conflicts = FALSE)
library(rlang, warn.conflicts = FALSE)
library(purrr, warn.conflicts = FALSE)
library(ggplot2, warn.conflicts = FALSE) # for the mpg data
# This function takes a data frame and a column name using tidyeval. It uses the
# column name both in a dplyr tidyeval context, and it also gets the column name
# as a string.
inner_function <- function(df, x) {
df %>%
distinct({{x}}) %>% # Use column name in dplyr tidyeval context
rename(level = {{x}}) %>%
mutate(term = rlang::as_name(rlang::enquo(x))) # Column name as string
}
# The function works when used by itself
mpg %>%
inner_function(drv)
#> # A tibble: 3 × 2
#> level term
#> <chr> <chr>
#> 1 f drv
#> 2 4 drv
#> 3 r drv
Created on 2023-06-29 with reprex v2.0.2