[R] inefficient ifelse() ?

From: ivo welch <ivowel_at_gmail.com>
Date: Tue, 01 Mar 2011 14:19:26 -0500


dear R experts---

  t <- 1:30
  f <- function(t) { cat("f for", t, "\n"); return(2*t) }
  g <- function(t) { cat("g for", t, "\n"); return(3*t) }
  s <- ifelse( t%%2==0, g(t), f(t))

shows that the ifelse function actually evaluates both f() and g() for all values first, and presumably then just picks left or right results based on t%%2. uggh... wouldn't it make more sense to evaluate only the relevant parts of each vector and then reassemble them?

/iaw



Ivo Welch

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 01 Mar 2011 - 19:27:49 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 01 Mar 2011 - 20:00:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive