Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a list of lists in R?

Tags:

r

I don't know how to make a list of lists in R. I have several lists, I want to store them in one data structure to make accessing them easier. However, it looks like you cannot use a list of lists in R, so if I get list l1 from another list, say, l2 then I cannot access elements l1. How can I implement it?

EDIT- I will show an example of what does not work for me:

list1 <- list() list1[1] = 1 list1[2] = 2 list2 <- list() list2[1] = 'a' list2[2] = 'b' list_all <- list(list1, list2) a = list_all[1] a[2] #[[1]] #NULL 

but a should be a list!

like image 627
ashim Avatar asked May 27 '12 19:05

ashim


People also ask

Can I make a list of lists in R?

The list is one of the most versatile data types in R thanks to its ability to accommodate heterogenous elements. A single list can contain multiple elements, regardless of their types or whether these elements contain further nested data. So you can have a list of a list of a list of a list of a list …

How do I make a list of items in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

Can we add another list in a list in R?

To add or append an element to the list in R use append() function. This function takes 3 parameters input list, the string or list you wanted to append, and position. The list. append() function from the rlist package can also use to append one list with another in R.


2 Answers

You can easily make lists of lists

list1 <- list(a = 2, b = 3) list2 <- list(c = "a", d = "b") mylist <- list(list1, list2) 

mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]. If you want to be able to something like mylist$list1 then you need to do somethingl like

mylist <- list(list1 = list1, list2 = list2) # Now you can do the following mylist$list1 

Edit: To reply to your edit. Just use double bracket indexing

a <- list_all[[1]] a[[1]] #[1] 1 a[[2]] #[1] 2 
like image 85
Dason Avatar answered Sep 23 '22 00:09

Dason


Using your example::

list1 <- list() list1[1] = 1 list1[2] = 2 list2 <- list() list2[1] = 'a' list2[2] = 'b' list_all <- list(list1, list2) 

Use '[[' to retrieve an element of a list:

b = list_all[[1]]  b [[1]] [1] 1  [[2]] [1] 2  class(b) [1] "list" 
like image 22
Matthew Lundberg Avatar answered Sep 26 '22 00:09

Matthew Lundberg