Nested lists let you store lists inside other lists. This helps organize related data in a simple way.
0
0
Nested lists in R Programming
Introduction
When you want to group different types of data together, like numbers and words.
When you need to store a list of lists, such as a table with rows and columns.
When you want to keep related information together, like a person's name and their scores.
When you want to pass complex data structures to functions.
When you want to build a tree-like structure with multiple levels.
Syntax
R Programming
nested_list <- list( element1, list( subelement1, subelement2 ), element3 )
You create a nested list by putting a list inside another list.
Use list() to create lists in R.
Examples
This is an empty nested list with no elements.
R Programming
empty_nested_list <- list()A nested list with one element inside another list.
R Programming
single_element_nested_list <- list(list(42))
A nested list with different types: a string, a list of numbers, and a boolean.
R Programming
mixed_nested_list <- list( "name" = "Alice", "scores" = list(90, 85, 88), "passed" = TRUE )
A nested list with multiple levels inside.
R Programming
deep_nested_list <- list( list( list(1, 2), list(3, 4) ), 5 )
Sample Program
This program creates a nested list with a person's info and scores. It prints the scores, adds a new score, then prints the updated scores.
R Programming
nested_list <- list( "person" = list( "name" = "Bob", "age" = 30 ), "scores" = c(95, 88, 92), "passed" = TRUE ) print("Before adding new score:") print(nested_list$scores) # Add a new score nested_list$scores <- c(nested_list$scores, 100) print("After adding new score:") print(nested_list$scores)
OutputSuccess
Important Notes
Access nested list elements using the $ operator or double square brackets [[ ]].
Time complexity to access an element is usually fast, but depends on depth.
Common mistake: forgetting to use list() inside list() to nest properly.
Use nested lists when you need to group related data hierarchically instead of flat vectors.
Summary
Nested lists store lists inside other lists to organize complex data.
Use list() to create nested lists and access elements with $ or [[ ]].
They help keep related data grouped and easy to manage.