Question

I would like to pass object met down to function sf but get object not found error. I think it might have to do with the environment of the top function call that it is not passed to the subfunction:

f <- function(fname,x,met=c('sum','subs')){

  .env <- environment() ## identify the environment
  do.call(fname,list(x,met),envir=.env)

}

sf <- function(x,...){

  if (met== 'sum') x + 100 else x - 100

}

f('sf',1:10,met='sum')
Was it helpful?

Solution

met cannot be referred to by name in the body of sf if it has not been explicitly passed as an argument of sf so try this:

sf <- function(x, met, ...) {
  if (met == 'sum') x + 100 else x - 100
}

If we assume met is the first component of ... in the call to sf (as is the case in the example in the question) then this works too:

sf <- function(x, ...) {
  met <- list(...)[[1]]
  if (met == 'sum') x + 100 else x - 100
}

And this more concise alternative works too:

sf <- function(x, ...) {
  met <- ...[[1]]
  if (met == 'sum') x + 100 else x - 100
}

And even more concise is this alternative:

sf <- function(x, ...) {
  met <- ..1
  if (met == 'sum') x + 100 else x - 100
}

We don't really need the env argument to do.call here.

UPDATE: Correction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top