如何从名称与值配对的列表中构建矩阵

时间:2011-06-08 15:58:35

标签: list r matrix

我有一个如下列表:

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

$b
[1] "b1" "b2"

$c
[1] "c1"

我想将其转换回矩阵,以便每个值与相应的名称配对。在此示例中,预期结果为:

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

实现这一目标的最有效方法是什么?

2 个答案:

答案 0 :(得分:3)

不知道效率最高,但使用您的列表:

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

我们可以使用sapply()

获取每个组件的长度
lens <- sapply(l, length)

我们只是重复l lens次的名称并取消列出l - 这里只需一行:

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

给出了所需的输出:

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"

答案 1 :(得分:2)

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"