While R ifelse incredibly convenient, it has a certain drawback: in the call to ifelse(test, yes, no) all elements yes and no are evaluated, even those that are thrown away.
This is pretty wasteful if you use it in the middle of a complex numerical exercise, say, in a function that will be passed to integrate , uniroot , optim or something else. For example, one could
ifelse(test, f(x, y, z), g(a, b, c))
where f and g are arbitrarily complex or slow functions, possibly involving more nested ifelse .
Has anyone written a replacement for ifelse that only evaluates the yes / no elements to be saved? In principle, something similar to
out <- test for(i in seq_along(out)) { if(test[i]) out[i] <- f(x[i], y[i], z[i]) else out[i] <- g(a[i], b[i], c[i]) }
but without the clumsiness / inefficiency of the explicit loop. Is this possible even if you do not get into the insides of R?
source share