[R] Using apply for logical conditions

Michael Lachmann lachmann at eva.mpg.de
Mon Aug 2 23:50:52 CEST 2010


Reduce() is really amazingly fast!

Even with a much larger number of columns, it is still in the same ballpark
(and much more readable):

> boolean <- c(TRUE, rep(FALSE,10^3))
> a<-matrix(sample(boolean, 10^7, replace = TRUE),10^4,10^3)
> b<-data.frame(a)
> system.time({opt4 <- rowSums(a, na.rm = TRUE) > 0})
   user  system elapsed 
  0.129   0.001   0.131 
> system.time({opt2 <- Reduce('|',b)})
   user  system elapsed 
  0.190   0.109   0.303 

and:
> boolean <- c(TRUE, rep(FALSE,10^4))
> a<-matrix(sample(boolean, 10^7, replace = TRUE),10^3,10^4)
> b<-data.frame(a)
> system.time({opt4 <- rowSums(a, na.rm = TRUE) > 0})
   user  system elapsed 
  0.082   0.001   0.083 
> system.time({opt2 <- Reduce('|',b)})
   user  system elapsed 
  0.205   0.001   0.209 

It seems to pretty much make rowSums obsolete, vs. Reduce('+'), except that
it works on lists, and converting a matrix to a data.frame takes ages.

-- 
View this message in context: http://r.789695.n4.nabble.com/Using-apply-for-logical-conditions-tp2310929p2311042.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list