Search code examples
rsymbols

how do i compactly pass multiple symbol arguments into a function?


I have created a dummy data frame (df) and want to derive a new column for each occurrence of 'col_x' in the data frame.

I have created a function which does this, although it requires entering the name of each column to be derived/derived from, as seen in example 1.

If i had a large number of columns this would look messy. I want to do something like in example 2, where i could pass a vector (arg in the example) to the function.

Example 2 doesn't actually work, as i'm using character strings in the vector. I guess i'd need a vector of symbols maybe? I'm not sure if that's possible though.

df <- data.frame(numbers = rep(5, 10), col_1 = sample(1:10, 10), col_2 = sample(1:10, 10), col_3 = sample(1:10, 10))


my_fun <- function(...){
  
  captured_expressions <- enexprs(...)
  
  len <- length(captured_expressions) / 2

  for(x in 1:len){
    y <- x + 3
    df <- df %>% mutate(!!captured_expressions[[y]] := !!captured_expressions[[x]] + numbers)
  }

print(df)
  
}

# example 1:
my_fun(col_1, col_2, col_3, col_1_derived, col_2_derived, col_3_derived)

arg <- append(paste0('col_', 1:3),
         paste0('col_', 1:3, '_derived'))

# example 2:
my_fun(arg)

Solution

  • I've solved this using a function i didn't know about called as.symbol.

    my_fun <- function(...){
    
      len <- length(...) / 2
      
      for(x in 1:len){
        y <- x + 3
        df <- df %>% mutate(!!as.symbol(...[y]) := !!as.symbol(...[x]) + numbers)
      }
      
      print(df)
    
    }