0Pricing
R Academy · Lesson

Named Vectors and Named Sequences

Assign and access names on vectors for readable code.

Named Vectors and Named Sequences is a free R Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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), '
')

The names() Function

names(x) retrieves the names of a vector as a character vector. You can also assign names after creation using names(x) <- c(...), which modifies the vector in place.

# Assign names after creation
temps <- c(22.1, 18.5, 25.3, 20.0)
cat('Before naming:', temps, '
')

names(temps) <- c('Mon', 'Tue', 'Wed', 'Thu')
cat('After naming:
')
print(temps)

# Retrieve names
cat('Days:', names(temps), '
')

Accessing Elements by Name

Access named vector elements using x["name"] or x[["name"]]. The single bracket [] returns a named subset; [[]] returns just the value without the name.

scores <- c(Math = 88, Science = 92, English = 75, History = 81)

# Single bracket: keeps name
cat('Math score (with name):
')
print(scores['Math'])

# Double bracket: just the value
cat('Science score (value only):', scores[['Science']], '
')

# Multiple names
cat('STEM subjects:
')
print(scores[c('Math', 'Science')])

setNames() for Functional Style

setNames(x, nm) returns a copy of x with names set to nm, without modifying the original. This is useful in pipelines where you want to name a vector as part of a chain of operations.

# setNames returns a named copy (does not modify original)
raw_values <- c(0.85, 0.72, 0.91, 0.68)
metrics <- setNames(raw_values, c('Precision', 'Recall', 'F1', 'Accuracy'))

cat('Original (unchanged):', raw_values, '
')
cat('Named metrics:
')
print(metrics)

# Best metric
best_name <- names(which.max(metrics))
cat('Best metric:', best_name, '=', metrics[best_name], '
')

Modifying Names

You can change individual names by indexing into names(x). This is useful when you need to rename a subset of elements without recreating the whole vector.

prices <- c(apple = 1.20, bannana = 0.80, cherry = 3.50)  # typo!

# Fix a single name
names(prices)[2] <- 'banana'
cat('Fixed names:
')
print(prices)

# Rename all
names(prices) <- c('Apple', 'Banana', 'Cherry')  # capitalise
cat('Capitalised:
')
print(prices)

Named Sequences with seq() and names()

You can create a named sequence by combining seq() with setNames(). This is especially useful for monthly or weekly indices where names add context to the numeric values.

# Monthly average temperature with names
temps_monthly <- setNames(
  c(3.1, 4.2, 8.5, 13.0, 17.2, 21.0, 23.5, 23.0, 19.0, 13.5, 7.8, 4.0),
  month.abb
)
cat('Monthly temps:
')
print(temps_monthly)
cat('Summer avg:', mean(temps_monthly[c('Jun', 'Jul', 'Aug')]), '
')

Filtering Named Vectors

Named vectors support both logical and character indexing. You can select elements by name and filter them by value at the same time, making named vectors very expressive for small lookup tables.

population <- c(Tokyo = 37.4, Delhi = 32.9, Shanghai = 28.5,
                Dhaka = 22.5, Cairo = 21.3, Mumbai = 20.7)

# Select cities with population > 25 million
big_cities <- population[population > 25]
cat('Cities over 25M:
')
print(big_cities)

# Sort descending by population
cat('Ranked:
')
print(sort(population, decreasing = TRUE))

Removing Names with unname()

unname(x) strips all names from a vector, returning just the values. This is useful when passing data to functions that do not expect named vectors, or when names add visual clutter to output.

named_vec <- c(x1 = 10, x2 = 20, x3 = 30, x4 = 40)
cat('Named:
')
print(named_vec)

unnamed_vec <- unname(named_vec)
cat('Unnamed:
')
print(unnamed_vec)

# Check
cat('Has names after unname:', !is.null(names(unnamed_vec)), '
')

Named Vectors as Lookup Tables

One of the most powerful uses of named vectors is as a lookup table: map from keys to values. Instead of a chain of if-else statements, use a named vector and index into it.

# Map month abbreviation to number of days
days_in_month <- c(Jan=31, Feb=28, Mar=31, Apr=30, May=31,
                   Jun=30, Jul=31, Aug=31, Sep=30, Oct=31,
                   Nov=30, Dec=31)

# Look up specific months
query <- c('Mar', 'Jul', 'Nov')
cat('Days in', query[1], ':', days_in_month[query[1]], '
')
cat('Days in', query[2], ':', days_in_month[query[2]], '
')
cat('Days in', query[3], ':', days_in_month[query[3]], '
')

Named Vectors: Key Facts

Summary of named vector features in R:

  • Create with c(name = value, ...) or assign via names(x) <- c(...)
  • Access by name with x['name'] (keeps name) or x[['name']] (value only)
  • setNames(x, nm) returns a named copy without modifying the original
  • unname(x) removes all names
  • Named vectors work as elegant lookup tables (replacing if-else chains)
# Complete workflow
rates <- c(USD = 1.0, EUR = 0.92, GBP = 0.79, JPY = 149.5)

# Convert 100 USD to each currency
amount_usd <- 100
converted <- amount_usd * rates
cat('100 USD in other currencies:
')
print(round(converted, 2))

Quick Check

What is the difference between x['key'] and x[['key']] when x is a named vector?

Recap: Named Vectors

Great work! Key takeaways from this lesson:

  • Named vectors pair each element with a character label
  • Create with c(name = val) syntax or assign with names(x) <- ...
  • x['name'] returns a named subset; x[['name']] returns just the value
  • setNames() is the functional (non-modifying) way to attach names
  • Use named vectors as lookup tables to replace verbose if-else chains
  • unname() strips names when raw values are needed
# Named vector as grade lookup
grade_map <- c('90'='A', '80'='B', '70'='C', '60'='D')
student_score <- 80

# Find grade bracket
brackets <- c(90, 80, 70, 60)
threshold <- max(brackets[brackets <= student_score])
cat('Score:', student_score, '-> Grade:', grade_map[as.character(threshold)], '
')

Frequently asked questions

Is the “Named Vectors and Named Sequences” lesson free?

Yes — the full text of “Named Vectors and Named Sequences” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Named Vectors and Named Sequences”?

Assign and access names on vectors for readable code. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Named Vectors and Named Sequences” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Colon Operator for Integer Ranges
  2. seq() for Custom Sequences
  3. rep() for Repeating Values
  4. Named Vectors and Named Sequences
← Back to R Academy