Emy
Emy

Reputation: 977

Subsetting a logical vector with a logical vector in R

(Note: following the suggestions in the comments, I have changed the original title "Comparing the content of two vectors in R?" to "Subsetting a logical vector with a logical vector in R")

I am trying to understand the following R code snippet (by the way, the question originated while I was trying to understand this example.)

I have a vector a defined as:

a = c(FALSE, FALSE)

Then I can define b:

b <-  a

I check b's content and everything looks OK:

b
#> [1] FALSE FALSE

Question

Now, what is the following code doing? Is it checking if b is equal to "not" a?

b[!a] 
#> [1] FALSE FALSE

But if I try b[a] the result is different:

b[a] 
#> logical(0)

I also tried a different example:

a = c(FALSE, TRUE)
b <-  a
b
#> [1] FALSE  TRUE

Now I try the same operations as above, but I get a different result:

b[!a] 
#> [1] FALSE
b[a] 
#> [1] TRUE

Created on 2021-03-23 by the reprex package (v0.3.0)

Upvotes: 2

Views: 1001

Answers (2)

AnilGoyal
AnilGoyal

Reputation: 26218

b[!a] will result in displaying those values of b which are at TRUE positions as evalauted by !a.

!a is actually T, T therefore displays first and second values of b which are F and F

More efficiently please see this

a <- 1:4
b <- c(T, T, F, T)

now a[!b] will display a[c(F, F, T, F)] i.e. only third element of a

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388972

[] is used for subsetting a vector. You can subset a vector using integer index or logical values.

When you are using logical vector to subset a vector, a value in the vector is selected if it is TRUE. In your example you are subsetting a logical vector with a logical vector which might be confusing. Let's take another example :

a <- c(10, 20)
b <- c(TRUE, FALSE)
a[b] 
#[1] 10

Since 1st value is TRUE and second is FALSE, the first value is selected.

Now if we invert the values, 20 would be selected because !b returns FALSE TRUE.

a[!b]
#[1] 20

Now implement this same logic in your example -

a = c(FALSE, FALSE)
b <- a

!b returns TRUE TRUE, hence both the values are selected when you do b[!a] and the none of the value is selected when you do b[a].

Upvotes: 2

Related Questions