Reputation: 33
I have two logical vectors.
a <- c(1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
b <- c(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, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
When I try to subset b to a like this
b[which(a == 1)]
everything is as I expect. However, like this
b[a]
I get different result.
Why? Probably the explanation is obvious but I completely don't understand...
Upvotes: 1
Views: 97
Reputation: 101317
As @akrun explained, you need logical values for subseting b
based on a
.
Below is another option to turn numeric a
to a logical one, e.g.,
> b[!!a]
[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 1 0 0 0 0 0 0 0 0 0 0 0 1
[39] 1 0 0 0
Upvotes: 0
Reputation: 887088
a
is a binary vector. It can be converted to boolean with as.logical
and then it will work as expected i.e. it will get the elements in 'b' that corresponds to TRUE values in 'a'
b[as.logical(a)]
because 0 is considered as FALSE whereas all other values can be TRUE
as.logical(c(1, 0, 2, 3))
#[1] TRUE FALSE TRUE TRUE
Otherwise, indexing starts in R
from 1 and the 1 value is selecting the first element based on the position, where as which(a == 1)
, gets the position of sequence from logical vector
b[c(1, 1, 0, 1)]
selects the first element of 'b' three times
whereas
b[which(c(1, 1, 0, 1) == 1)]
gets the position as 1, 2, 4 for selecting the 'b'
which(c(1, 1, 0, 1) == 1)
#[1] 1 2 4
Upvotes: 0