Table of Contents
Creating a list of lists in R allows for the organization and storage of multiple lists within a single data structure. This can be achieved by using the list() function and specifying each list as an element within the main list. For example, a list of lists in R can be created as follows:
list_of_lists
Create a List of Lists in R (With Example)
You can use the following basic syntax to create a list of lists in R:
#define lists list1 <- list(a=5, b=3) list2 <- list(c='A', d='B') #create list of lists list_of_lists <- list(list1, list2)
The following example shows how to use this syntax in practice.
Example: Create List of Lists in R
The following code shows how to create a list that contains 3 lists in R:
#define lists list1 <- list(a=5, b=3) list2 <- list(c='A', d=c('B', 'C')) list3 <- list(e=c(20, 5, 8, 16)) #create list of lists list_of_lists <- list(list1, list2, list3) #view the list of lists list_of_lists [[1]] [[1]]$a [1] 5 [[1]]$b [1] 3 [[2]] [[2]]$c [1] "A" [[2]]$d [1] "B" "C" [[3]] [[3]]$e [1] 20 5 8 16
We can then use single brackets [ ] to access a specific list.
For example, we can use the following syntax to access the second list:
#access second list
list_of_lists[2]
[[1]]
[[1]]$c
[1] "A"
[[1]]$d
[1] "B" "C"We can also use double brackets [[ ]] and the dollar sign operator $ to access a specific element within a specific list.
For example, we can use the following syntax to access element d within the second list:
#access element 'd' within second list
list_of_lists[[2]]$d
[1] "B" "C"
You can use similar syntax to access any element within any list.
The following tutorials explain how to perform other common tasks with lists in R:
Cite this article
stats writer (2024). How can I create a list of lists in R, and what is an example of this?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-i-create-a-list-of-lists-in-r-and-what-is-an-example-of-this/
stats writer. "How can I create a list of lists in R, and what is an example of this?." PSYCHOLOGICAL SCALES, 27 Jun. 2024, https://scales.arabpsychology.com/stats/how-can-i-create-a-list-of-lists-in-r-and-what-is-an-example-of-this/.
stats writer. "How can I create a list of lists in R, and what is an example of this?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-i-create-a-list-of-lists-in-r-and-what-is-an-example-of-this/.
stats writer (2024) 'How can I create a list of lists in R, and what is an example of this?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-i-create-a-list-of-lists-in-r-and-what-is-an-example-of-this/.
[1] stats writer, "How can I create a list of lists in R, and what is an example of this?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. How can I create a list of lists in R, and what is an example of this?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
