[英]How to save matrices within a loop in R
I have written the following script:我编写了以下脚本:
library(igraph)
library(MASS)
for(i in 1:1000){
g01 <- erdos.renyi.game(10, .50, directed = FALSE)
E(g01)$weight <- runif(length(E(g01)), 0, 12)
plot(g01, edge.width=E(g01)$weight)
p <-as_adjacency_matrix(g01, attr="weight")
s<-print(p)}
Now, I wish to save the output generated (ie 1000 10X10 matrices) How should I go about it?现在,我想保存生成的output(即1000个10X10的矩阵)我应该如何处理go呢?
Awaiting a reply & thank you, Ishani Mukherjee等待回复并感谢您,Ishani Mukherjee
You could write the matrix into a list during each step of the loop and then retrieve the each matrix from the list:您可以在循环的每个步骤中将矩阵写入列表,然后从列表中检索每个矩阵:
library(igraph)
library(MASS)
x <- list() ### create a list where the matrices go
for(i in 1:1000)
{
g01 <- erdos.renyi.game(10, .50, directed = FALSE)
E(g01)$weight <- runif(length(E(g01)), 0, 12)
plot(g01, edge.width=E(g01)$weight)
p <-as_adjacency_matrix(g01, attr="weight")
x[[ i ]] <- p ### in each step of the loop, write the matrix into the list
# s<-print(p) ### no need to print
}
Retrieve:取回:
> x[[ 555 ]]
10 x 10 sparse Matrix of class "dgCMatrix"
[1,] . 11.861884 4.374968 2.579739 11.131786 . .
[2,] 11.861884 . . . 3.426191 . .
[3,] 4.374968 . . 1.892858 4.843295 . 6.359838
[4,] 2.579739 . 1.892858 . . 8.204216 5.829073
[5,] 11.131786 3.426191 4.843295 . . . 6.004565
[6,] . . . 8.204216 . . 3.570526
[7,] . . 6.359838 5.829073 6.004565 3.570526 .
[8,] 11.716666 . . . 2.965670 3.122152 8.271782
[9,] . 2.790694 . . . 9.142040 2.037214
[10,] . 2.233465 . . . . .
[1,] 11.716666 . .
[2,] . 2.790694 2.233465
[3,] . . .
[4,] . . .
[5,] 2.965670 . .
[6,] 3.122152 9.142040 .
[7,] 8.271782 2.037214 .
[8,] . . .
[9,] . . .
[10,] . . .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.