将矩阵转换为列表

编程入门 行业动态 更新时间:2024-10-27 08:31:07
本文介绍了将矩阵转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个矩阵foo,如下所示:

Suppose I have a matrix foo as follows:

foo <- cbind(c(1,2,3), c(15,16,17)) > foo [,1] [,2] [1,] 1 15 [2,] 2 16 [3,] 3 17

我想将其变成一个看起来像

I'd like to turn it into a list that looks like

[[1]] [1] 1 15 [[2]] [1] 2 16 [[3]] [1] 3 17

您可以按照以下步骤进行操作:

You can do it as follows:

lapply(apply(foo, 1, function(x) list(c(x[1], x[2]))), function(y) unlist(y))

我对没有那么复杂的替代方法感兴趣.请注意,如果您只是执行apply(foo, 1, function(x) list(c(x[1], x[2]))),它将返回列表中的一个列表,我希望避免这种情况.

I'm interested in an alternative method that isn't as complicated. Note, if you just do apply(foo, 1, function(x) list(c(x[1], x[2]))), it returns a list within a list, which I'm hoping to avoid.

推荐答案

这是一个更干净的解决方案:

Here's a cleaner solution:

as.list(data.frame(t(foo)))

这利用了一个事实,即数据帧实际上只是等长向量的列表(而矩阵实际上是一个显示有列和行的向量...您可以通过调用foo [5]来看到这一点) (例如).

That takes advantage of the fact that a data frame is really just a list of equal length vectors (while a matrix is really a vector that is displayed with columns and rows...you can see this by calling foo[5], for instance).

您也可以这样做,尽管并没有太大改善:

You could also do this, although it isn't much of an improvement:

lapply(1:nrow(foo), function(i) foo[i,])

更多推荐

将矩阵转换为列表

本文发布于:2023-10-27 03:48:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532219.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   转换为   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!