Named Vectors
A named vector gives each item its own label, like a name tag on each locker. You can then ask for a value by its name instead of its position.
In this page:
Syntax
vector_name <- c(name1 = value1, name2 = value2)
names(vector_name) <- c("name1", "name2")
vector_name["name1"]
Named Vectors
A vector's elements can have names, assigned with names() or directly with c(a = 1, b = 2), letting you access elements by name instead of position.
Named vectors behave like a simple lookup table. Names are stored as an attribute alongside the vector's values.
Note:
Named vectors are a lightweight alternative to a dictionary/hash map for simple key-value data.
Example: Named Vectors
ages <- c(alice = 30, bob = 25, cara = 40)
print(ages)
cat("Bob's age:", ages["bob"], "\n")
print(names(ages))
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
ages[bob]without quotes, which looks for a variablebob; useages["bob"]. - Expecting
ages["bob"]to return just the number, when it returns a named vector; useages[["bob"]]to drop the name. - Adding a name that does not exist and expecting an error, when
ages["dan"]givesNA.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: