Search code examples
rtidyevalquosure

Convert list of symbols to character string in own function


I have the following data frame:

dat <- data.frame(time   = runif(20),
                  group1 = rep(1:2, times = 10),
                  group2 = rep(1:2, each = 10),
                  group3 = rep(3:4, each = 10))

I'm now writing a function my_function that takes the following form:

my_function(data, time_var = time, group_vars = c(group1, group2))

If I'm not mistaken, I'm passing the group_vars as symbols to my function, right?

However, within my function I want to first do some error checks if the variables passed to the function exist in the data. For the time variable I was successful, but I don't know how I can turn my group_vars list into a vector of strings so that it looks like c("group1", "group2").

My current function looks like:

my_function <- function (data, time_var = NULL, group_vars = NULL)
{
  time_var          <- enquo(time_var)
  time_var_string   <- as_label(time_var)
  group_vars        <- enquos(group_vars)

  # is "time" variable part of the dataset?
  if (!time_var_string %in% colnames(data))
  {
    stop(paste0("The variable '", time_var_string, "' doesn't exist in your data set. Please check for typos."))
  }
}

And I want to extend the latter part so that I can also do some checks in the form of !group_vars %in% colnames(data). I know I could pass the group_var variables already as a vector of strings to the function, but I don't want to do that for other reasons.


Solution

  • If you'd like to use c() in this way, chances are you need selections. One easy way to take selections in an argument is to interface with dplyr::select():

    my_function <- function(data, group_vars = NULL) {
      group_vars <- names(dplyr::select(data, {{ group_vars }}))
      group_vars
    }
    
    mtcars %>% my_function(c(cyl, mpg))
    #> [1] "cyl" "mpg"
    
    mtcars %>% my_function(starts_with("d"))
    #> [1] "disp" "drat"