Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R how to obtain a vector which would apply AND over all columns?

Tags:

r

I am trying to apply AND over all columns of a matrix and could not find a similar question:

> array(c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE),dim=c(2,3))
      [,1] [,2]  [,3]
[1,]  TRUE TRUE FALSE
[2,] FALSE TRUE FALSE

I am trying to obtain

      [,1]  [,2]  [,3]
[1,]  FALSE TRUE FALSE

By doing an AND over columns, how do I do that in R ?

like image 414
BlueTrin Avatar asked Dec 01 '25 19:12

BlueTrin


2 Answers

Use all():

apply(x, 2, all)
[1] FALSE  TRUE FALSE

You didn't ask for it, but any() is the complement of all():

apply(x, 2, any)
[1]  TRUE  TRUE FALSE
like image 176
Andrie Avatar answered Dec 03 '25 12:12

Andrie


The fastest way I know of:

colSums(x) == nrow(x)

And if you are code-golfing, there is the more obscure

!colSums(!x)

Also, if your data only has two rows, you can just do the vectorized

x[1,] & x[2,]

All of these should be way faster than using a loop (for or *apply)


Finally, to get the result into a horizontal matrix, wrap everything into t(...) or matrix(..., nrow = 1).

like image 20
flodel Avatar answered Dec 03 '25 13:12

flodel



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!