Accessing List Elements
Part of the Fundamentals section of Coddy's R journey — lesson 72 of 78.
Lists use a different syntax for accessing elements compared to vectors. The key difference is between single brackets [ ] and double brackets [[ ]].
Double brackets extract the actual element from the list:
my_list <- list(42, "hello", TRUE)
print(my_list[[1]])Output:
[1] 42Single brackets return a sublist containing the element, not the element itself:
my_list <- list(42, "hello", TRUE)
print(my_list[1])Output:
[[1]]
[1] 42This distinction matters when you want to work with the actual value. If a list element is a vector, double brackets let you access it directly and then use vector indexing:
my_list <- list(c(10, 20, 30), "text")
print(my_list[[1]][2])Output:
[1] 20Here, my_list[[1]] retrieves the vector, and [2] accesses its second element. Remember: use [[ ]] when you need the actual content, and [ ] when you want a smaller list.
Challenge
EasyYou will receive two lines of input:
- Three comma-separated values of different types (e.g.,
100,hello,TRUE) - A comma-separated list of numbers representing a vector to be stored as the fourth element (e.g.,
5,10,15,20)
Perform the following operations:
- Create a list with four elements: the numeric value, the text, the logical value, and the vector of numbers
- Use double brackets to extract and print the second element (the text value)
- Use single brackets to extract the third element and print the result (notice the difference in output format)
- Access the vector stored in the fourth element using double brackets, then extract and print its third value using vector indexing
- Print the sum of all numbers in the fourth element (access the vector with double brackets and use
sum())
For example, if the inputs are:
42,world,FALSE
8,16,24,32,40The output should be:
[1] "world"
[[1]]
[1] FALSE
[1] 24
[1] 120Explanation:
my_list[[2]]extracts the actual text value: "world"my_list[3]returns a sublist containing FALSE (note the[[1]]in output)my_list[[4]][3]accesses the vector, then gets its third element: 24sum(my_list[[4]])calculates 8+16+24+32+40 = 120
Cheat sheet
Lists use different bracket syntax for accessing elements:
Double brackets [[ ]] extract the actual element:
my_list <- list(42, "hello", TRUE)
print(my_list[[1]]) # Output: [1] 42Single brackets [ ] return a sublist containing the element:
my_list <- list(42, "hello", TRUE)
print(my_list[1]) # Output: [[1]] [1] 42Accessing nested elements: Use double brackets to extract a vector from a list, then use vector indexing:
my_list <- list(c(10, 20, 30), "text")
print(my_list[[1]][2]) # Output: [1] 20Use [[ ]] when you need the actual content, and [ ] when you want a smaller list.
Try it yourself
# Read input
con <- file("stdin", "r")
input1 <- suppressWarnings(readLines(con, n = 1)) # First line: three comma-separated values
input2 <- suppressWarnings(readLines(con, n = 1)) # Second line: comma-separated numbers for vector
close(con)
# Parse the first input line into separate values
values <- strsplit(input1, ",")[[1]]
numeric_val <- as.numeric(values[1])
text_val <- values[2]
logical_val <- as.logical(values[3])
# Parse the second input line into a numeric vector
vector_val <- as.numeric(strsplit(input2, ",")[[1]])
# TODO: Write your code below
# 1. Create a list with four elements: numeric_val, text_val, logical_val, and vector_val
# 2. Use double brackets [[ ]] to extract and print the second element
# 3. Use single brackets [ ] to extract the third element and print it
# 4. Access the fourth element with double brackets, then extract its third value
# 5. Print the sum of all numbers in the fourth elementThis 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