I have a list like 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 paired with the corresponding name. In this example the expected result is:
[,1] [,2]
[1,] "a" "a1"
[2,] "a" "a2"
[3,] "b" "b1"
[4,] "b" "b2"
[5,] "c" "c1"
What is the most efficient way to achie开发者_StackOverflow社区ve that?
Don't know about most efficient, but using your list:
l <- list(a=c("a1","a2"), b=c("b1","b2"), c="c1")
we can get the length of each component using sapply()
lens <- sapply(l, length)
the we just rep the names of l
lens
number of times and unlist l
- here done in a single line:
cbind(rep(names(l), times = sapply(l, length)), unlist(l))
which gives the desired output:
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"
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"
精彩评论