Reputation: 11
How do I extract the rows of m
where a
is even? For example,
m = matrix(1:24, 6)
a = c(3, 4, 1, 1, 2, 5)
Upvotes: 1
Views: 2190
Reputation: 18323
Your question is a little ambiguous, but I think I know what you mean. For your data:
m = matrix(1:24, 6)
a = c(3, 4, 1, 1, 2, 5)
You could mean that you want to select all the rows in m
where a
is even. So, in this case, you would want the second and fifth rows of m
, because only the second and fifth element of a
is even. In this case, this would work:
m[a %% 2 ==0,]
I think, however, you meant that you wanted to find the numbers in a
that were even, (in this case 2 and 4) and then select those rows of m
. In that case, you would use:
m[a[a %% 2 ==0],]
So that would select first the fourth, and then the second row of m. Remember, however, that if you have any even number in there twice, it will select the row twice.
If you wanted to select the rows in order (row 2 and then row 4) you would do:
m[sort(a[a %% 2 ==0]),]
Upvotes: 6