Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Convert list of symbols to character string in own function

$
0
0

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.


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>