Search code examples
rfunctiondplyrtidyeval

tidyeval: convert a character string to a variable in a dplyr function


I am having trouble passing a character string into a function that uses dplyr.

First I have a simple version that produces the output I want but is not called the way I want.

Next I show a version where I call the function they way I want to call it, even though that version does not work.

This produces the results I want:

car_column <- function(d,Column,Value,Regex) {
 d %>%  
    filter(str_detect(car_name, regex('mazda', ignore_case = TRUE))) %>% 
    rename(Measurement = mpg) %>%  
    select(car_name, Measurement)
}
mtcars %>% 
  tibble::rownames_to_column() %>%  
  rename(car_name = rowname) %>% 
  car_column(car_name, mpg, "mazda")

This codes calls the function as I want to call it. Note that "car_name" is hard coded in this function definition, but should be changed to "Column".

car_column <- function(d,Column,Value,Regex, Statistic) {
 d %>% 
  filter(str_detect(car_name, regex(Regex, ignore_case = TRUE))) %>% 
    rename({{Statistic}}:= {{Value}}) %>% 
  select({{Column}}, {{Statistic}})
}
mtcars %>% 
  tibble::rownames_to_column() %>%  
  rename(car_name = rowname) %>% 
  car_column("car_name", "mpg", "mazda","Measurement")

Solution

  • As the input argument is string, convert it to symbol and evalute (!!)

    car_column <- function(d,Column,Value,Regex, Statistic) {
     d %>% 
      filter(str_detect(!! rlang::sym(Column), regex(Regex, ignore_case = TRUE))) %>% 
       rename({{Statistic}}:= {{Value}}) %>% 
       select({{Column}}, {{Statistic}})
      }
    
    mtcars %>% 
       tibble::rownames_to_column() %>%  
       rename(car_name = rowname) %>% 
       car_column("car_name", "mpg", "mazda","Measurement")
    #       car_name Measurement
    #1     Mazda RX4          21
    #2 Mazda RX4 Wag          21