Reputation: 587
I want to take a logical matrix and and
all of the columns in the matrix together to create a vector. An example:
a = c(TRUE, TRUE, FALSE, TRUE, FALSE, FALSE)
A = matrix(a, nrow = 3, ncol = TRUE, byrow = TRUE)
I would like to produce
[1] TRUE FALSE FALSE
Currently I am doing this with
apply(A, 1, function(x) Reduce('&', x))
However, this goes very slow with the size of my input, and I was wondering if there was a more efficient way to do this.
Upvotes: 0
Views: 20
Reputation: 887078
Instead of using Reduce
within apply
, an option would be to either convert the 'A' to data.frame
and then do
Reduce(`&`, as.data.frame(A))
#[1] TRUE FALSE FALSE
Or split
by col
and then
Reduce(`&`, split(A, col(A)))
#[1] TRUE FALSE FALSE
Upvotes: 1
Reputation: 3875
It will be faster to use:
apply(A,1,all)
instead of a call to Reduce
.
Also, the rowSums
function is equivalent to apply(x,1,sum)
but much faster, so it will probably be even faster to do:
rowSums(A)==ncol(A)
Upvotes: 1