Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse a logical vector with AND or OR?

How can I apply the AND & or OR| operators to a logical vector in R?

For example:

a <- c(FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,FALSE)

Is there a simple way to

  • Are all elements TRUE? Like putting an & between each element:
    • when applied to the above vector it would return: FALSE
  • Are any elements TRUE? Like putting a | between each element
    • when applied to the above vector it would return: TRUE
like image 763
xiao Avatar asked Oct 14 '25 17:10

xiao


2 Answers

allTrue <- all(a)
anyTrue <- any(a)

The documentation for these functions is linked from help("&") or help("|").

like image 98
Ben DeVries Avatar answered Oct 17 '25 05:10

Ben DeVries


all and any are exactly what you are after, alternatively:

sum(a)==length(a) # Are all elements TRUE?

sum(a)>0 # Are any elements TRUE?
like image 37
989 Avatar answered Oct 17 '25 06:10

989



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!