[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 1
[3,] 0 1 0
[4,] 0 0 1
[5,] 1 0 0
Given a matrix like that above - what is an efficient way to iterate over the matrix, selecting rows for which the first element is 1 and all other elements are 0, such that
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 1 0 0
is returned?
Thanks, D.
Recreate the data:
a <- array(c(1,0,0,0,1,0,1,1,0,0,0,1,0,1,0), dim=c(5,3))
Now create a vector that equals the condition.
cond <- c(1, 0, 0)
Next, an apply
statement wrapped in a call to which
will tell you which rows match your condition
which(apply(a, 1, function(x)all(x==cond)))
1] 1 5
Finally, to extract the rows where this condition is met:
x <- which(apply(a, 1, function(x)all(x==cond)))
a[x, ]
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 1 0 0
The resulting array doesn't contain much information. Perhaps you wanted to know how many rows match the condition?
length(x)
[1] 2
To answer the follow-on question. How to create a condition vector when the array is large?
Well, one way is as follows. Let's say you have an array of 100 columns wide, so you need a vector of 100 in length, and you want the third element to be a 1:
cond <- rep(0, 100)
cond[3] <- 1
cond
[1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0