将矩阵转换为列表 [英] converting a matrix to a list
问题描述
假设我有一个矩阵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,])
这篇关于将矩阵转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!