Suppose I have a set of variables x, ythat may or may not be defined. These variables are passed to a function with a name test.
y <- 10
test <- function(a,b) { ifelse(a > b, "hello", "world") }
test(x,y)
If I called test(x,y)when x was not created, R will throw an error "object" x "not found".
If I add to the check for availability, the function works when called from a global environment
y <- 10
test <- function(a,b) {
print(exists(as.character(substitute(a))))
if (!exists(as.character(substitute(a)))) {a <- 0}
ifelse(a > b, "hello", "world")
}
test(x,y)
x <- 11
test(x,y)
[1] TRUE
[1] "hello"
However, if I complete test(x,y)inside the function blah. It cannot find an existing variable.
rm(list=ls())
test <- function(a,b) {
print(exists(as.character(substitute(a))))
if (!exists(as.character(substitute(a)))) {a <- 0}
ifelse(a > b, "hello", "world")
}
blah <- function() { x <- 11; y <- 10; test(x,y)}
blah()
[1] FALSE -- expecting TRUE
[1] "world" -- expecting "hello"
I suppose the failure is due to the fact that he is not looking into the right environment. Any idea how I can get this to work correctly?
source
share