is %in% performing magic or am I just blind?

Hello lovely R Community,

So there this crazy output in my r-code which I couldnt understand. The Code is quite simple so I have a Subset table$id of the set a$id.

all(table$id %in% a$id)
[1] TRUE

but now this is happening:

length(table$id)
[1] 8081

but

bool3 <- a$id %in% table$id
sum(bool3)
[1] 8064

Is this even possible?

The operator %in% tests elements of the left vector for membership in the right vector:

some_letters <- sample(letters, 10)
letters
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q"
#> [18] "r" "s" "t" "u" "v" "w" "x" "y" "z"
some_letters
#>  [1] "s" "o" "u" "a" "d" "m" "b" "f" "i" "h"
letters %in% some_letters
#>  [1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE
#> [12] FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE
#> [23] FALSE FALSE FALSE FALSE
some_letters %in% letters
#>  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Created on 2020-02-20 by the reprex package (v0.3.0)

1 Like

It is perfectly possible, and hence there's no magic. Unfortunately, I have no information to make any inference on your eyesight, though.

Consider a <- c(1, 2), and b <- c(1, 2, 3).

Then, if you do all(a %in% b), it'll be TRUE, as a is a subset of b. But, if you do sum(b %in% a), that will be just 2, and not 3 because b is not a subset of a.

Hope this helps.

1 Like

yes thanks a lot! I think I just needed a small break :smiley:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.