Consider the R code :
foo <- function(formula){
Y <- get(formula[[2]])
print(Y)
}
main <- function(){
Y <- 1
X <- 2
foo(Y ~ X)
}
main()
The outcome says that in get(formula[[2]])
, it cannot find object Y
.
How can I make a function read formula in a local setting?
How do I change the code so that it runs and prints Y
?
By default get
will look for Y
in the the current environment of the call to get
, which is just what is available in foo
itself (i.e. pos = -1
). One of the nice things about R formulas is that they have an associated environment as an attribute, so we can specify to get
that it should look in that environment instead:
foo <- function(formula){
Y <- get(formula[[2]], environment(formula))
print(Y)
}
main()
[1] 1
Specifying the environment is a good idea generally, so that e.g. this will still get the Y
from the original context:
foo <- function(formula){
Y <- 3
bar <- get(formula[[2]], environment(formula))
print(bar)
}