Manipulating Vectors

Accessing Vector Elements

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 y
y[3]
[1] "c"
# Select the second through fifth elements of y
y[2:5]
[1] "b" "c" "d" "e"
# Select the fourth, sixth, seventh, and eighth elements of y
y[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", respectively
y[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.

y[8:10] <- "alice"
y
 [1] "bob"   "b"     "c"     "foo"   "e"     "bar"   "g"     "alice" "alice"
[10] "alice"
y[1:3] <- c("hello", "world")
Warning in y[1:3] <- c("hello", "world"): number of items to replace is not a
multiple of replacement length
y
 [1] "hello" "world" "hello" "foo"   "e"     "bar"   "g"     "alice" "alice"
[10] "alice"
## Extra elements in the replacement vector are dropped with a warning
y[1:4] <- c("It", "was", "the", "best", "of", "times")
Warning in y[1:4] <- c("It", "was", "the", "best", "of", "times"): number of
items to replace is not a multiple of replacement length
y
 [1] "It"    "was"   "the"   "best"  "e"     "bar"   "g"     "alice" "alice"
[10] "alice"
Practice
  1. Create an integer vector called myVec that contains all the whole numbers from 1 to 11.
  2. Use a single command to replace all the even numbers in myVec with 0.
myVec <- 1:11
myVec[seq(2, 10, 2)] <- 0
myVec
 [1]  1  0  3  0  5  0  7  0  9  0 11
Back to top