← Back to R Course | Chapter 3: Vectors | Lesson 4 of 7

Vector Indexing

Vector indexing picks items from a list by their position, and R starts counting at one. It is like asking for the third book on a shelf.

In this page:

  1. Vector Indexing
Syntax
r
vector_name[index]
vector_name[c(index1, index2)]
vector_name[-index]
vector_name[start:end]

Vector Indexing

R vectors are indexed starting at 1, not 0, using square brackets like v[3]. You can also index with a vector of positions, like v[c(1, 3)], to pull out multiple elements at once.

Negative indices, like v[-1], exclude that position instead of selecting it.

Warning: R indexing starts at 1, not 0 -- v[1] is the first element, unlike most other programming languages.

Example: Vector Indexing

markup
v <- c(10, 20, 30, 40, 50)

cat(v[1], "\n")
print(v[c(1, 3)])
print(v[-1])
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using 0 as the first index, when v[0] returns an empty vector and the first element is v[1].
  2. Using v[-1] and expecting the last element, when it removes the first and returns the rest.
  3. Indexing beyond the length, like v[10], which returns NA and not an error.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.