Named Vectors
Part of the Fundamentals section of Coddy's R journey — lesson 62 of 78.
So far, you've accessed vector elements using numeric positions. But what if you could access them by meaningful names instead? Named vectors let you assign labels to each element, making your code more readable and self-documenting.
You can create a named vector by providing names during creation:
ages <- c(alice = 25, bob = 30, charlie = 28)
print(ages)Output:
alice bob charlie
25 30 28To access elements by name, use the name as a string inside square brackets:
print(ages["bob"])Output:
bob
30You can also add names to an existing vector using the names() function:
scores <- c(85, 92, 78)
names(scores) <- c("math", "science", "english")
print(scores["math"])Output:
math
85Named vectors are especially useful when working with data that has natural labels, like storing student grades by subject or prices by product name.
Challenge
EasyYou will receive two lines of input:
- A comma-separated list of product names (e.g.,
laptop,phone,tablet,headphones) - A comma-separated list of corresponding prices (e.g.,
999,699,449,199)
Perform the following operations:
- Create a numeric vector from the prices
- Assign the product names to the vector using the
names()function - Print the entire named vector
- Print the price of the second product by accessing it using its name
- Print the price of the last product by accessing it using its name
For example, if the inputs are:
apple,banana,orange,grape
2,1,3,4The output should be:
apple banana orange grape
2 1 3 4
banana
1
grape
4Note: Access the second and last elements by their names (as strings), not by numeric index.
Cheat sheet
Named vectors allow you to assign labels to each element, making elements accessible by meaningful names instead of just numeric positions.
Create a named vector by providing names during creation:
ages <- c(alice = 25, bob = 30, charlie = 28)Access elements by name using the name as a string inside square brackets:
ages["bob"] # Returns the element named "bob"Add names to an existing vector using the names() function:
scores <- c(85, 92, 78)
names(scores) <- c("math", "science", "english")
scores["math"] # Returns 85Try it yourself
# Read input
con <- file("stdin", "r")
products_input <- suppressWarnings(readLines(con, n = 1))
prices_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# Parse the comma-separated inputs
product_names <- strsplit(products_input, ",")[[1]]
price_values <- strsplit(prices_input, ",")[[1]]
# TODO: Write your code below
# 1. Create a numeric vector from the prices
# 2. Assign the product names to the vector using names()
# 3. Print the entire named vector
# 4. Print the price of the second product by accessing it using its name
# 5. Print the price of the last product by accessing it using its nameThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values