The documentation of do.call
states:
If
quote
isFALSE
, the default, then the arguments are evaluated (in the calling environment, not inenvir
).
This sentence would suggest to me that when quote = FALSE
, specifying envir
makes no difference. However, that's not the case, and in fact I've encountered cases where I need to specify envir
to get the function to work.
Simplest reproducible example:
g1 <- function(x) {
args <- as.list(match.call())
args[[1]] <- NULL # remove the function call
do.call(print, args, quote = FALSE) # call print()
}
g2 <- function(x) {
args <- as.list(match.call())
args[[1]] <- NULL # remove the function call
do.call(print, args, quote = FALSE, envir = parent.frame()) # call print(), specifying envir
}
h1 <- function(x, y) {
g1(x*y)
}
h2 <- function(x, y) {
g2(x*y)
}
With these functions, h2()
behaves as one would think but h1()
does not:
h1(2, 3)
#Error in print(x) : object 'y' not found
h2(2, 3)
#[1] 6
y <- 100
h1(2, 3)
#[1] 600
## Looks like g1() took the value of y from the global environment
h2(2, 3)
#[1] 6
Can anybody explain to me what's going on here?
Note: There's a related post here but by my reading the answers don't specifically state what do.call()
does with the envir
variable.