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

发布于 2024-11-14 06:14:55 字数 344 浏览 1 评论 0原文

我有一个如下所示的列表:

> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生寂 2024-11-21 06:14:55

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

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"

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"
酒几许 2024-11-21 06:14:55
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"
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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文