R Vector Indexing
Vector indexing selects values from a vector by their position. Square brackets hold the positions to select.
Picking by position
Square brackets select values by position. Position 1 gives the first value and position 3 gives the third value.
v <- c(10, 20, 30, 40)
print(v[1])
print(v[3])Zero and negative positions
Position 0 selects nothing from the vector. A negative position drops that value and keeps the rest.
v <- c(10, 20, 30, 40)
print(v[0])
print(v[-1])Picking several and filtering
One selection picks positions 1 and 3 together. The other selection keeps only the values above 15.
v <- c(10, 20, 30, 40)
print(v[c(1, 3)])
print(v[v > 15])Testing membership
The %in% operator tests whether a value sits in the vector. 20 sits in the vector and 99 does not.
v <- c(10, 20, 30, 40)
print(20 %in% v)
print(99 %in% v)Picking by name
This vector carries a name for each position. Selecting by the name b gives back the value 20.
v <- c(10, 20, 30)
names(v) <- c("a", "b", "c")
print(v["b"])Example
v <- c(10, 20, 30, 40)
print(v[10])
print(v[2])Key points
- Positions in a vector start at 1.
- The first value sits at position 1.
- Position 0 selects nothing and gives back an empty result.
- A negative position drops that value and keeps all the others.
- A test inside the brackets keeps only the values that pass the test.
- The %in% operator tests whether a value sits in a vector.
- Reading past the end of a vector gives NA.
- NA is the marker for a missing value and a later lesson covers it in full.
In this example, position 10 does not exist in a vector of length 4 so the result is NA. Position 2 exists and gives back 20.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does v[1] give back for a vector v?