简体   繁体   中英

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?

Awaiting a reply & thank you, 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,]  .        .        .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM