繁体   English   中英

如何在 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)}

现在,我想保存生成的output(即1000个10X10的矩阵)我应该如何处理go呢?

等待回复并感谢您,Ishani Mukherjee

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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