문제

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')
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top