How to build a matrix from a list associating names with values

I have a list similar to the following:

> l <- list(a=c("a1","a2"), b=c("b1","b2"), c="c1")
> l
$a
[1] "a1" "a2"

$b
[1] "b1" "b2"

$c
[1] "c1"

I would like to convert it back to a matrix so that each value is conjugated with a corresponding name. In this example, the expected result:

     [,1] [,2]
[1,] "a"  "a1"
[2,] "a"  "a2"
[3,] "b"  "b1"
[4,] "b"  "b2"
[5,] "c"  "c1"

What is the most effective way to achieve this?

+3
source share
2 answers

I do not know about the most effective ones, but using your list:

l <- list(a=c("a1","a2"), b=c("b1","b2"), c="c1")

we can get the length of each component with sapply()

lens <- sapply(l, length)

we just l lensretype the names a number of times and unlist l- here it is executed on one line:

cbind(rep(names(l), times = sapply(l, length)), unlist(l))

which gives the desired result:

R> cbind(rep(names(l), times = sapply(l, length)), unlist(l))
   [,1] [,2]
a1 "a"  "a1"
a2 "a"  "a2"
b1 "b"  "b1"
b2 "b"  "b2"
c  "c"  "c1"
+3
source
cbind(rep(names(l), sapply(l, length)), unlist(l))

   [,1] [,2]
a1 "a"  "a1"
a2 "a"  "a2"
b1 "b"  "b1"
b2 "b"  "b2"
c  "c"  "c1"
+2
source

All Articles