如何从名称与值配对的列表构建矩阵
我有一个如下所示的列表:
> 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"
实现该目标的最有效方法是什么?
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 achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不知道最有效,但使用您的列表:
我们可以使用
sapply()
获取每个组件的长度,我们只需代表
l
Lens
次数并取消列出l
- 此处在一行中完成:给出所需的输出:
Don't know about most efficient, but using your list:
we can get the length of each component using
sapply()
the we just rep the names of
l
lens
number of times and unlistl
- here done in a single line:which gives the desired output: