We obtain the results because the logical vector is recycled (as its length is only 5 compared to length(a)
which is 10) to meet the end of the 'a' vector i..e
i1 <- rep(!c(10,0,8,6,0), length.out = length(a))
i1
[1] FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE
If we use that vector
a[i1]
[1] 4 10 14 20
It is easier to understand if we just pass TRUE
, then the TRUE is recycled to return all the elements or the reverse with FALSE
a[TRUE]
[1] 2 4 6 8 10 12 14 16 18 20
a[FALSE]
numeric(0)
The recycling is mentioned in the documentation of ?Extract
For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. i, j, ... can also be negative integers, indicating elements/slices to leave out of the selection.
In most of the languages, 0 is considered as FALSE and other values as TRUE. So, when we negate the 0 (FALSE) is converted to TRUE and all others to FALSE