Named Vectors and Named Sequences
Assign and access names on vectors for readable code.
Introduction to Named Vectors
A named vector is a vector where each element has an associated name (a character label). Names make code more readable and allow you to access elements by name instead of position index.
# A plain vector vs a named vector
plain <- c(78, 92, 85, 67)
named <- c(Alice = 78, Bob = 92, Carol = 85, Dave = 67)
cat('Plain vector:', plain, '
')
cat('Named vector:
')
print(named)Creating Named Vectors with c()
The simplest way to create a named vector is to use name = value pairs inside c(). Names can be any valid string; if they contain spaces or special characters, wrap them in backticks or quotes.
# GDP in trillions USD
gdp <- c(USA = 27.4, China = 18.0, Germany = 4.1,
Japan = 4.2, UK = 3.1)
cat('GDP values:
')
print(gdp)
cat('Names:', names(gdp), '
')
cat('Values:', unname(gdp), '
')All lessons in this course
- The Colon Operator for Integer Ranges
- seq() for Custom Sequences
- rep() for Repeating Values
- Named Vectors and Named Sequences