We can access specific elements in a vector using the square bracket selection operator, []. To select specific elements, provide an integer vector defining the positions of the desired elements.
# Define some vector(y <- letters[1:10])
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
# Select the third entry in yy[3]
[1] "c"
# Select the second through fifth elements of yy[2:5]
[1] "b" "c" "d" "e"
# Select the fourth, sixth, seventh, and eighth elements of yy[c(4, 6, 8, 7)]
[1] "d" "f" "h" "g"
# Same as above but combining c() and : y[c(4, 6:8)]
[1] "d" "f" "g" "h"
When selecting vector elements, we must use a single vector to index the target elements.
y[2, 3]
Error in y[2, 3]: incorrect number of dimensions
Specifying multiple arguments inside [] is reserved for multi-dimensional structures like matrices or data frames and will trigger an error with vectors.
Modifying Vector Elements
Above, we used the selection operator, [], to extract vector elements, but you shouldn’t think about that operator as a “subsetting operator”. I prefer to think about the selection operator as designating some part of a vector for further processing. In the above examples, the further processing was simply printing the selected elements to the R console, but we can also use the selection operators to modify the designated vector elements.
We can overwrite vector elements with new values by selecting the target elements using the [] operator and assigning new values with the ordinary assignment operator, <-.
# Replace the first elements of y with "bob"y[1] <-"bob"y
[1] "bob" "b" "c" "d" "e" "f" "g" "h" "i" "j"
# Replace the fourth and sixth elements of y with "foo" and "bar", respectivelyy[c(4, 6)] <-c("foo", "bar")y
[1] "bob" "b" "c" "foo" "e" "bar" "g" "h" "i" "j"
Overwriting vector elements uses ordinary recycling to harmonize the lengths of the selected set of elements and the length of the replacement vector.