For this example, we will use the vector:
> x <- 11:20
> x
[1] 11 12 13 14 15 16 17 18 19 20
R vectors are 1-indexed, so for example x[1]
will return 11
. We can also extract a sub-vector of x
by passing a vector of indices to the bracket operator:
> x[c(2,4,6)]
[1] 12 14 16
If we pass a vector of negative indices, R will return a sub-vector with the specified indices excluded:
> x[c(-1,-3)]
[1] 12 14 15 16 17 18 19 20
We can also pass a boolean vector to the bracket operator, in which case it returns a sub-vector corresponding to the coordinates where the indexing vector is TRUE
:
> x[c(rep(TRUE,5),rep(FALSE,5))]
[1] 11 12 13 14 15 16
If the indexing vector is shorter than the length of the array, then it will be repeated, as in:
> x[c(TRUE,FALSE)]
[1] 11 13 15 17 19
> x[c(TRUE,FALSE,FALSE)]
[1] 11 14 17 20