user1447630
user1447630

Reputation: 293

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

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
 ...

Upvotes: 17

Views: 6358

Answers (1)

Tyler Rinker
Tyler Rinker

Reputation: 110062

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

Upvotes: 32

Related Questions