I need to evaluate two functions f and g which are both computationally expensive elementwise conditional on the outcome of a test. An advantage of ifelse seems to be that it does vectorized testing and only returns the fitting elements from f and g. So if we have
ifelse(test, f(y), g(y))
where y some large vector ifelse returns a vector of length(y) with elements f(y) where test==T and g(y) else.
Is this done computationally efficient? It would not be, when ifelse first evaluates both f and g for all y and then only returns those elements of the resulting two return vectors indicated by the test result. It would be if it only evaluate f and g for those elements indicated by test; thus saving the computation time for those elements for which f and g are not returned.
Aucun commentaire:
Enregistrer un commentaire