如何在 R 中的循环中保存矩阵

How to save matrices within a loop in R

我写了以下脚本:

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)}

现在,我希望保存生成的输出(即 1000 个 10X10 矩阵) 我该怎么办?

等待回复 & 谢谢, 伊沙尼慕克吉

您可以在循环的每个步骤中将矩阵写入列表,然后从列表中检索每个矩阵:

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
}

检索:

> 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,]  .        .        .