2

I am new to R. I have created an object a: a <- c(2,4,6,8,10,12,14,16,18,20)

I have performed the following operation on the vector: a[!c(10,0,8,6,0)] and I get the output as 4 10 14 20

I do understand that !c(10,0,8,6,0) produces the output as FALSE TRUE FALSE FALSE TRUE

I don't understand how the final results comes out to be 4 10 14 20

Can someone help?

KacZdr
  • 1,267
  • 3
  • 8
  • 23

1 Answers1

3

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

akrun
  • 874,273
  • 37
  • 540
  • 662