Looking for a more efficient ifelse ()

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?

+6
source share
1 answer

I do not think the problem is ifelse . f and g are evaluated only once in your expression. I think your problem is that f and g slow with vectors.

You can change the calls to f and g so that they are evaluated only by a subset of the vector.

 out <- numeric(length(test)) #or whatever the output type is out[test] <- f(x[test], y[test], z[test]) out[!test] <- g(x[!test], y[!test], z[!test]) 

You will need to adjust this if any test items are equal to NA .

+6
source

Source: https://habr.com/ru/post/905795/


All Articles