Skip to content
Prev 324981 / 398503 Next

recode: how to avoid nested ifelse

I still argue for na.rm=FALSE, but that is cute, also substantially faster

f1 <- function(x1, x2, x3) do.call(paste0, list(x1, x2, x3))
f2 <- function(x1, x2, x3) pmax(3*x3, 2*x2, es, 0, na.rm=FALSE)
f3 <- function(x1, x2, x3) Reduce(`+`, list(x1, x2, x3))
f4 <- function(x1, x2, x3) rowSums(cbind(x1, x2, x3))

es <- rep(c(0, 0, 1, 0, 1, 0, 1, 1, NA, NA), 1000)
hs <- rep(c(0, 0, 1, 0, 1, 0, 1, 0, 1, NA), 1000)
cg <- rep(c(0, 0, 0, 0, 1, 0, 1, 0, NA, NA), 1000)

system.time(replicate(1000, f1(cg, hs, es)))
system.time(replicate(1000, f2(cg, hs, es)))
system.time(replicate(1000, f3(cg, hs, es)))
system.time(replicate(1000, f4(cg, hs, es)))
user  system elapsed
  22.73    0.03   22.76
user  system elapsed
   0.92    0.04    0.95
user  system elapsed
   0.19    0.02    0.20
 > system.time(replicate(1000, f4(cg, hs, es)))
   user  system elapsed
   0.95    0.03    0.98


R version 3.0.0 (2013-04-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
On Fri, Jun 7, 2013 at 7:25 PM, Neal Fultz <nfultz at gmail.com> wrote: