Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

R vector: Access several elements (slice)

  • We can use a vector as the index of anther vector thereby fetching a new vector of the specific values.
  • We can also select a range of elements using :
distances = c(11, 12, 13, 14, 15, 16, 17, 18)

print(distances[c(2, 4)])  # 12, 14
print(distances[2:4])  # 12, 13, 14


locations = c(5, 3, 5, 7)
nd = distances[locations]

print(nd)            # 15, 13, 15, 17
print(distances)