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:
Syntax
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
v <- c(10, 20, 30, 40, 50)
cat(v[1], "\n")
print(v[c(1, 3)])
print(v[-1])
Login to try C/C++/Java/PHP code in the editor
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
- Using 0 as the first index, when
v[0]returns an empty vector and the first element isv[1]. - Using
v[-1]and expecting the last element, when it removes the first and returns the rest. - Indexing beyond the length, like
v[10], which returnsNAand not an error.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: