Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from a list of lists to a list in R retaining names?

Tags:

r

If I have a list of lists of character vectors:

 l1 <- list(a=list(x=c(1,4,4),y=c(24,44)),
       b=list(x=c(12,3)),
       c=list(x=c(3,41),y=c(3214,432),z=c(31,4,5,1,45)))

 > l1
 $a
 $a$x
 [1] 1 4 4

 $a$y
 [1] 24 44
 ...

How can I convert this into a single flat list retaining names?

 > wantedList
 $ax
 [1] 1 4 4

 $ay
 [1] 24 44
 ...
like image 460
user1447630 Avatar asked May 20 '13 19:05

user1447630


People also ask

How do you make a list of lists 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 a list contain a list 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 convert something to a list in R?

list() Function. as. list() function in R Programming Language is used to convert an object to a list.

How do I create a list vector in R?

Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.


1 Answers

Use:

unlist(l1, recursive=FALSE)

## > unlist(l1, recursive=FALSE)
## $a.x
## [1] 1 4 4
## 
## $a.y
## [1] 24 44
## 
## $b.x
## [1] 12  3
## 
## $c.x
## [1]  3 41
## 
## $c.y
## [1] 3214  432
## 
## $c.z
## [1] 31  4  5  1 45
like image 51
Tyler Rinker Avatar answered Nov 16 '22 01:11

Tyler Rinker