chl111
chl111

Reputation: 488

How to use ellipsis to pass arguments and evaluate in another environment in R

I am trying to pass quite a lot of arguments to a function (actually it's a reference class initialize function). I am thinking about using three dots ellipsis to pass arguments to the class initializer, but it doesn't work. Here is my sample code:

SomeClass<-setRefClass("SomeClass",
                       fields=list(a="numeric",b="numeric",c="character"))

SomeClass_1<-setRefClass("SomeClass_1",contains="SomeClass")

SomeClass_2<-setRefClass("SomeClass_2",contains="SomeClass")

getExpression<-function(...){
  return(substitute(list(...)))
}

ex1<-getExpression(a=1:3,b=pmax(2:4,3:5),c=c("test","test1","test2"))

d<-TRUE

if(d){
  newclass<-SomeClass_1(do.call(eval,as.list(ex1)))
     }else{
  newclass<-SomeClass_2(do.call(eval,as.list(ex1)))
          }

It gives me error messages:

Error in (function (expr, envir = parent.frame(), enclos = if     (is.list(envir) ||  : 
  unused arguments (a = 1:3, b = pmax(2:4, 3:5), c = c("test", "test1", "test2"))

I am not sure how to evaluate a bunch of arguments to initialize a reference class? Please share your thoughts; thanks in advance!

Upvotes: 2

Views: 325

Answers (1)

MrFlick
MrFlick

Reputation: 206232

Do you really need to delay evaluation of the parameters? Seems like

getExpression <- function(...){
  return(list(...))
}
ex1 <- getExpression(a=1:3,b=pmax(2:4,3:5),c=c("test","test1","test2"))
do.call("SomeClass_1", ex1)
do.call("SomeClass_2", ex1)

Would work better. If you want to expand the parameters for the class call, that call needs needs to be invoked with the do.call, not just the parameters.

Upvotes: 2

Related Questions