简体   繁体   English

使用索引在R中的循环后命名矩阵

[英]Use index to name a matrix after a loop in R

Please excuse my naive question. 请原谅我的幼稚问题。

I have a loop which returns in every step, a matrix b . 我有一个循环,它在每一步中都返回矩阵b I would like to save each matrix from each loop, under a different name depending on the iteration number. 我想根据迭代次数以不同的名称保存每个循环中的每个矩阵。 For example, at the end of the first iteration, I want to get the matrix named b1 , at the end of the second iteration the b2 etc... 例如,在第一次迭代结束时,我想获取名为b1的矩阵,在第二次迭代结束时获取b2等。

As an example, lets use the following code: 例如,让我们使用以下代码:

count=0
a=matrix(c(1,2,3,4,5,6,7,8,9,10,11,12), nrow=6)
for (count in 1:10)  {
  b<-cbind(a[,1],matrix(c( a[sample(nrow(a)),2]), nrow=nrow(a)) ) 
  print(b)
}
count+1

Here, the original matrix is matrix a which has 6 rows and 2 columns. 在此,原始矩阵是具有62列的matrix a I permute the order of the elements in the second column. 我在第二列中排列了元素的顺序。 The resulting matrix b , is the matrix that conatins as first column the first column of the original matrix a and as second column the permuted second column of a . 将得到的matrix b ,是作为conatins第一列中的原始的第一列的矩阵matrix a的排列的第二列和作为第二塔a

Can anyone help me? 谁能帮我?

You really don't want to store these as separate variables- it would be much better to keep them as a list of 10 matrices. 您确实不想将它们存储为单独的变量-最好将它们保留为10个矩阵的列表。 That could be done very easily using replicate : 这可以很容易地使用来完成replicate

lst = replicate(10, cbind(a[,1],matrix(c( a[sample(nrow(a)),2]), nrow=nrow(a)) ),
          simplify=FALSE)

You can then access any of the 10 matrices like this: 然后,您可以像这样访问10个矩阵中的任何一个:

lst[[1]]
#     [,1] [,2]
#[1,]    1    7
#[2,]    2   10
#[3,]    3   11
#[4,]    4    8
#[5,]    5    9
#[6,]    6   12

Similarly, you could loop over them like this: 同样,您可以像这样循环遍历它们:

for (m in lst) {
    print(m)
    # do something with your matrix m
}

As told before, list is a better option. 如前所述,列表是一个更好的选择。 But, if you still want to save each interation on different variables, you can use assign() 但是,如果您仍然想将每个插值保存在不同的变量中,则可以使用assign()

count=0
a=matrix(c(1,2,3,4,5,6,7,8,9,10,11,12), nrow=6)
for (count in 1:10)  {
  assign(paste('b',count,sep=''),cbind(a[,1],matrix(c( a[sample(nrow(a)),2]), nrow=nrow(a))))
}
b1
b2

As said in other option it is better to use a list. 如其他选择所述,最好使用列表。 Here a version using sapply to get pretty named result: 这里是一个使用sapply获得漂亮命名结果的版本:

 res <- sapply(paste('b',1:10,sep=''), 
           function(x) cbind(a[,1],matrix(c( a[sample(nrow(a)),2]), nrow=nrow(a)) ),
       simplify=F)

Then To get matrix b5 for example, 然后以矩阵b5为例,

res$b5

   [,1] [,2]
[1,]    1    9
[2,]    2    7
[3,]    3    8
[4,]    4   11
[5,]    5   10
[6,]    6   12

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

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