# Here we want to return a list of all variables created inside a function
f <- function(a = 1, b = 2) {
x <- 3
y <- 4
return(locals(without = formalArgs(caller(4))))
# We need to go 4 frames up, to catch the formalArgs of `f`, because the
# `caller(4)` argument is not evaluated directly be `formalArgs`.
}
f() # returns either list(x = 3, y = 4) or list(y = 4, x = 3)
# The same result could have been achieved as follows
g <- function(a = 1, b = 2) {
x <- 3
y <- 4
func <- caller(1)
return(locals(without = c("func", formalArgs(func))))
}
g() # returns either list(x = 3, y = 4) or list(y = 4, x = 3)
Run the code above in your browser using DataLab