我有一个如下列表:
> 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"
实现这一目标的最有效方法是什么?
答案 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"