Reputation: 10063
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 ?
Upvotes: 3
Views: 82
Reputation: 89057
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)
.
Upvotes: 5
Reputation: 179418
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
Upvotes: 8