R function '…' argument scope

2019-08-30 07:14发布

问题:

Tried this code via source()

f1 <- function(x, ...){
  print(y)
}

f1(x = 1, y = 2)

or this code via source()

f1 <- function(x, ...){
  y <- 2
  f2(x, y = y, ...)
}

f2 <- function(x, ...){
  print(y)
}

f1(x = 1)

Got this Error

Error in print(y) : object 'y' not found

I guess the '...' argument takes from the global environment?

回答1:

you should call y in your function as correct like this

f1 <- function(x, ...){
l <- list(...)
if(!is.null(l$y)) print(l$y)
}
f1(x = 1, y=2)