7.1 Numerical Indexing

With numerical indexing, you enter a vector of integers corresponding to the values in the vector you want to access in the form a[index], where a is the vector, and index is a vector of index values. For example, let’s use numerical indexing to get values from our boat vectors.

# What is the first boat name?
boat.names[1]
## [1] "a"

# What are the first five boat colors?
boat.colors[1:5]
## [1] "black" "green" "pink"  "blue"  "blue"

# What is every second boat age?
boat.ages[seq(1, 5, by = 2)]
## [1] 143 356 647

You can use any indexing vector as long as it contains integers. You can even access the same elements multiple times:

# What is the first boat age (3 times)
boat.ages[c(1, 1, 1)]
## [1] 143 143 143

If it makes your code clearer, you can define an indexing object before doing your actual indexing. For example, let’s define an object called my.index and use this object to index our data vector:

my.index <- 3:5
boat.names[my.index]
## [1] "c" "d" "e"