Randy Minder - 2 months ago 5x

R Question

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.

Answer

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.

Source (Stackoverflow)

Comments