如何从 R 中的向量列表创建矩阵?
目标:从相等长度的向量列表中创建一个矩阵,其中每个向量成为一行。
示例:
> a <- list()
> for (i in 1:10) a[[i]] <- c(i,1:5)
> a
[[1]]
[1] 1 1 2 3 4 5
[[2]]
[1] 2 1 2 3 4 5
[[3]]
[1] 3 1 2 3 4 5
[[4]]
[1] 4 1 2 3 4 5
[[5]]
[1] 5 1 2 3 4 5
[[6]]
[1] 6 1 2 3 4 5
[[7]]
[1] 7 1 2 3 4 5
[[8]]
[1] 8 1 2 3 4 5
[[9]]
[1] 9 1 2 3 4 5
[[10]]
[1] 10 1 2 3 4 5
我想要:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Goal: from a list of vectors of equal length, create a matrix where each vector becomes a row.
Example:
> a <- list()
> for (i in 1:10) a[[i]] <- c(i,1:5)
> a
[[1]]
[1] 1 1 2 3 4 5
[[2]]
[1] 2 1 2 3 4 5
[[3]]
[1] 3 1 2 3 4 5
[[4]]
[1] 4 1 2 3 4 5
[[5]]
[1] 5 1 2 3 4 5
[[6]]
[1] 6 1 2 3 4 5
[[7]]
[1] 7 1 2 3 4 5
[[8]]
[1] 8 1 2 3 4 5
[[9]]
[1] 9 1 2 3 4 5
[[10]]
[1] 10 1 2 3 4 5
I want:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
一种选择是使用 do.call():
One option is to use
do.call()
:simplify2array
是一个相当直观的基本函数。但是,由于 R 的默认设置是首先按列填充数据,因此您需要转置输出。 (sapply
使用simplify2array
,如help(sapply)
中所述。)simplify2array
is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply
usessimplify2array
, as documented inhelp(sapply)
.)内置的
matrix
函数有一个很好的选项来byrow
输入数据。将其与源列表中的unlist
结合起来将为您提供一个矩阵。我们还需要指定行数,以便分解未列出的数据。那是:The built-in
matrix
function has the nice option to enter databyrow
. Combine that with anunlist
on your source list will give you a matrix. We also need to specify the number of rows so it can break up the unlisted data. That is:并不简单,但它有效:
Not straightforward, but it works:
其中“a”是一个列表。
适用于不相等的行大小
where 'a' is a list.
Would work for unequal row size
如果您的列表元素大小不等或者您实际上想要一个
data.frame
,那么data.table::transpose(a)
可能是一个有用的工具。它有效地将长度为 n 的长度为 p 的向量列表转换为长度为 p 的长度为 n 的向量列表,并用您选择的值填充缺失的元素。
它几乎与 Matrix(unlist(
), byrow=TRUE)
解决方案一样快,并且比t(sapply(
) 方法快得多也适用于不等长度。data.table::transpose(a)
can be a useful tool here if you your list elements have unequal size or you actually wanted adata.frame
instead.It efficiently turns a length-n list of length-up-to-p vectors into a length-p list of length-n vectors, padding the missing elements with a value of your choice.
It is almost as fast as the
matrix(unlist(
), byrow=TRUE)
solution and much faster than thet(sapply(
approach that also works for unequal lengths.