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

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:

  1. Named Vectors
Syntax
r
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

markup
ages <- c(alice = 30, bob = 25, cara = 40)

print(ages)
cat("Bob's age:", ages["bob"], "\n")
print(names(ages))
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 ages[bob] without quotes, which looks for a variable bob; use ages["bob"].
  2. Expecting ages["bob"] to return just the number, when it returns a named vector; use ages[["bob"]] to drop the name.
  3. Adding a name that does not exist and expecting an error, when ages["dan"] gives NA.
🔒

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.