[R] Using apply for logical conditions

Joshua Wiley jwiley.psych at gmail.com
Mon Aug 2 23:28:38 CEST 2010


On Mon, Aug 2, 2010 at 2:08 PM, Michael Lachmann <lachmann at eva.mpg.de> wrote:
>
> Reduce() is much nicer, but I usually use
>
> rowSums(A) > 0 for 'or', and
> rowSums(A) == ncols for 'and'.
>
> Which works slightly faster.

For the sake of my own curiosity, I compared several of these options,
but in case others are interested.....

> boolean <- c(TRUE, FALSE, FALSE)
>
> set.seed(1)
> mydata <- data.frame(X = sample(boolean, 10^7, replace = TRUE),
+                      Y = sample(boolean, 10^7, replace = TRUE),
+                      Z = sample(boolean, 10^7, replace = TRUE))
>
> system.time(opt1 <- apply(mydata, 1, any))
   user  system elapsed
 147.26    0.42  148.56
> system.time(opt2 <- Reduce('|', mydata))
   user  system elapsed
   0.33    0.00    0.35
> system.time(opt3 <- as.logical(rowSums(mydata, na.rm = TRUE)))
   user  system elapsed
   0.25    0.00    0.27
> system.time(opt4 <- rowSums(mydata, na.rm = TRUE) > 0)
   user  system elapsed
   0.25    0.00    0.25
>
> identical(opt1, opt2)
[1] TRUE
> identical(opt1, opt3)
[1] TRUE
> identical(opt1, opt4)
[1] TRUE
>
> rm(boolean, mydata, opt1, opt2, opt3, opt4)



>
> I noticed, though, that Reduce() doesn't work on matrices. Is there an
> alternative for matrices, or do you have to convert the matrix first to a
> data.frame, and then use Reduce?
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-apply-for-logical-conditions-tp2310929p2310991.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list