[英]For Loop storing output as list to then combine into matrix
I have a list of matrices I would like to first convert into individual vectors then combine them into one large matrix. 我有一个矩阵列表,我想首先将其转换成单个向量,然后将它们组合成一个大矩阵。 I have been trying to implement a for loop to do this and have been unable to do so with any success. 我一直在尝试实现一个for循环来执行此操作,但无法成功完成。
Example data: 5 10x10 matrices in a list 示例数据:列表中5个10x10矩阵
m1 <- matrix(1:100, nrow = 10, ncol = 10)
m2 <- matrix(1:100, nrow = 10, ncol = 10)
m3 <- matrix(1:100, nrow = 10, ncol = 10)
m4 <- matrix(1:100, nrow = 10, ncol = 10)
m5 <- matrix(1:100, nrow = 10, ncol = 10)
mylist <- list(m1, m2, m3, m4, m5)
I can turn an individual matrix into a vector using the following: 我可以使用以下方法将单个矩阵转换为向量:
unlist(mylist[1])
My for loop is as follows, and currently outputs them all into a single vector: 我的for循环如下,当前将它们全部输出到单个向量中:
z = list()
for (i in mylist[length(mylist)]) {
n <- unlist(mylist)
z <- c(n)
}
length(z)
[1] 500
The output I would like would be the df: 我想要的输出将是df:
m1 <- unlist(mylist[1])
m2 <- unlist(mylist[2])
m3 <- unlist(mylist[3])
m4 <- unlist(mylist[4])
m5 <- unlist(mylist[5])
df <- cbind(m1, m2, m3, m4, m5)
Any help would be great! 任何帮助将是巨大的! Thanks! 谢谢!
To use a for loop, I would do it like this: 要使用for循环,我会这样做:
z = list()
for (i in seq_along(mylist)) {
z[[i]] = c(mylist[[i]])
}
But when you're just applying a simple function to each list element, lapply
is very nice: 但是,当您仅对每个列表元素应用一个简单的函数时, lapply
非常好:
z = lapply(mylist, c)
If you then want to cbind
all of these vectors, we can either use Reduce
or do.call
: 如果然后您想cbind
所有这些向量,我们可以使用Reduce
或do.call
:
do.call(what = cbind, args = z)
Reduce(f = cbind, x = z)
The do.call
is equivalent to cbind(z[[1]], z[[2]], z[[3]], ...)
, and the Reduce
is equivalent to cbind(z[[1]], cbind(z[[2]], cbind(z[[3]], ...)))
. do.call
等效于cbind(z[[1]], z[[2]], z[[3]], ...)
,而Reduce
等效于cbind(z[[1]], cbind(z[[2]], cbind(z[[3]], ...)))
。 Since cbind
accepts any number of arguments, do.call
is probably nicer. 由于cbind
接受任意数量的参数,所以do.call
可能更好。 You would need Reduce
if you wanted to add or multiply the vectors, for example. 例如,如果要添加或乘以向量,则需要使用Reduce
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.