I have two nested ifelse
statements in a function. When I call the function, it fails because a variable in the last else
clause is undefined - even if that clause is not reached.
x <- factor(c("a", "b", "c", "d"))
h <- "hi"
l <- "lo"
Now undefined variable m
is never used, but this produces an error:
ifelse(as.numeric(x) > 2, h,
ifelse(as.numeric(x) < 3, l, m))
Error in ifelse(as.numeric(x) < 3, l, m) : object 'm' not found
Even though all four values of x
satisfy the first two if
conditions:
> sum(as.numeric(x) > 2 | as.numeric(x) < 3)
[1] 4
Edit: I intentionally haven't defined m
in this example, but I'd like to know how this is evaluated such that R looks for m
when the last clause is never reached.