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
...
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.
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 …
list() Function. as. list() function in R Programming Language is used to convert an object to a list.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With