Element selection
Let's now examine how elements can be selected from various class features.
Selecting elements from vectors
At this point in the chapter, you probably already suspect that in order to select specific items from a vector, the selection condition must be enclosed in []
.
There are basically three ways of selecting elements from arrays in R. They are as follows:
- By index: A set of integers that indicate the position of the elements to select:
> LETTERS[c(1,5,6)] [1] "A" "E" "F"
Note
LETTERS
is a character vector built-in object in R that contains the entire alphabet in upper case. For lower case, useLETTERS
.Using negative subscripts removes specific elements from an object (unlike in languages such as Python, where it implies reverse order):
> LETTERS[-c(1,5,6)] [1] "B" "C" "D" "G" "H" "I" "J" "K" "L" "M" "N" "O" "...