Use eval (substitute ()) for multiple expressions

I asked a question earlier How to accept a text / character argument without quotes . In the script I provided in this question, the number of arguments is fixed, so the number of eval (substitute ()) that I use in the definition of the function corresponds to the number of arguments that I have.

Now I have a script in which I have one argument, for example factors (see below), and the user can specify several column names without using quotes around them, i.e. they will use factor1 instead of "factor1" . And I would like to evaluate each of the column names provided by the user.

 foo<-function(data.frame, factors){ } 

Question 1: I wonder if there is a way to apply eval (substitute ()) to multiple expressions when the number of expressions can change.

As stated, eval (substitute ()) can be potentially dangerous and may fail under certain circumstances.

Question 2: so there is a more elegant way to solve the problem, except using the column names shown below:

 foo<-function(data.frame, factors){ output<-data.frame[, factors] output } foo(data.frame=dataset, factors=c("factor1", "factor2")) 
+6
source share
1 answer

First of all, in the example you provided, I would prefer to use quoted column names. One thing in their favor is that they will allow us to use useful indirection as follows:

 XX <- c("cyl", "mpg") foo(mtcars, XX) 

However, if you want to pass a character vector without quotes, this refers to your Question 2 .

 foo <- function(data, factors) { jj <- as.character(substitute(factors)[-1]) data[,jj] } head(foo(data = mtcars, factors = c(cyl, mpg))) # cyl mpg # Mazda RX4 6 21.0 # Mazda RX4 Wag 6 21.0 # Datsun 710 4 22.8 # Hornet 4 Drive 6 21.4 # Hornet Sportabout 8 18.7 # Valiant 6 18.1 
+7
source

All Articles