sisdog
sisdog

Reputation: 2719

R Filter Not Working as Expected

Novice R question: why is my boolean vector not filtering as expected below? I don't know why it's only filtering the first element and not the 3rd and 5th also.

> nums = seq(1,6); nums
[1] 1 2 3 4 5 6
> filter = c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)
> nums[filter]
[1] 1 3 5      #<<==WORKS AS EXPECTED
> nums[-filter]
[1] 2 3 4 5 6  #<<==NOT EXPECTED, EXPECTING 2 4 6

BTW, I have tried this and it works but I thought you could omit items from a vector subset with the negative sign...

> nums[!filter]
[1] 2 4 6

Upvotes: 2

Views: 235

Answers (2)

markdly
markdly

Reputation: 4534

Here is a worked example illustrating what @Glen has already said when - or ! is used in front of filter.

filter = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)

-filter
#> [1] -1  0 -1  0 -1  0

!filter
#> [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE

Hence, passing -filter means the first column is dropped from nums

Upvotes: 1

Glen
Glen

Reputation: 1772

Since -filter returns -1,0,-1,0,-1,0, I assume R is returning nums[-1] and ignoring the rest of the -filter vector. Obviously !filter is the correct way to proceed.

Upvotes: 3

Related Questions