0

I saw the following in an example on subsetting, and I don't understand it as I'm still fairly new to R.

x <- c(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9)
x[c(TRUE, TRUE, FALSE, FALSE)]
[1] 1.1 2.2 5.5 6.6 9.9

I understand the creation of the vector of numerics. But I don't understand how or why the result is generated by subsetting using the boolean values.

Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • 1
    Good explanation of recycling [here](http://stackoverflow.com/questions/13461829/r-how-to-list-every-other-element/13462110) – Rich Scriven Aug 13 '16 at 17:00

1 Answers1

2

This is clearly a recycling issue. The logical vector gets recycled to the end of the vector and returns the values wherever the TRUE is found. To illustrate it create a logical vector with rep

i1 <- rep(c(TRUE, TRUE, FALSE, FALSE), length.out=9)
i1
#[1]  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE

and subset the vector

x[i1]
#[1] 1.1 2.2 5.5 6.6 9.9

The recyling also does the same thing i.e. repeating the vector of logical elements until it reaches the end of the vector.

akrun
  • 874,273
  • 37
  • 540
  • 662