Page 25 - Applied Statistics with R
P. 25
3.2. DATA STRUCTURES 25
length(x)
## [1] 6
length(y)
## [1] 100
3.2.1.1 Subsetting
To subset a vector, we use square brackets, [].
x
## [1] 1 3 5 7 8 9
x[1]
## [1] 1
x[3]
## [1] 5
We see that x[1] returns the first element, and x[3] returns the third element.
x[-2]
## [1] 1 5 7 8 9
We can also exclude certain indexes, in this case the second element.
x[1:3]
## [1] 1 3 5
x[c(1,3,4)]
## [1] 1 5 7
Lastly we see that we can subset based on a vector of indices.
All of the above are subsetting a vector using a vector of indexes. (Remember a
single number is still a vector.) We could instead use a vector of logical values.

