简体   繁体   English

如何在R的for循环中将索引传递给对象的名称?

[英]How to pass an index to the name of an object in a for loop in R?

I am trying to figure out how to have R accept my index within a for loop.我想弄清楚如何让 R 在 for 循环中接受我的索引。 As a simple example, I would like each new matrix to have a name index that is different than the one before:作为一个简单的例子,我希望每个新矩阵都有一个与之前不同的名称索引:

for(i in 1:5){
new.matrix.i <- matrix(NA, nrow = i, ncol = i)
}

From this loop, I know it obviously doesn't work, but was wondering how I could create 5 new matrices, with the first being a one-by-one matrix of NA, and the second a two-by-two matrix of NA's, all the way to a five-by-five matrix with all NA's.从这个循环中,我知道它显然不起作用,但想知道我如何创建 5 个新矩阵,第一个是 NA 的一对一矩阵,第二个是 NA 的两两矩阵,一直到包含所有 NA 的 5×5 矩阵。

In other words, I am wondering how to have R treat换句话说,我想知道如何让 R 治疗

new.matrix.i新矩阵.i

with i as a dynamic name instead of just a regular name for a matrix?将 i 作为动态名称而不是矩阵的常规名称? Thanks!谢谢!

We can use lapply to create a list of matrices我们可以使用lapply创建一个matrices list

lst <- lapply(1:5, function(i)  matrix(NA, nrow = i, ncol = i))

Or we proceed with for loop, initialize the new.matrix.i as a list或者我们继续for循环,将new.matrix.i初始化为一个list

new.matrix.i <- vector("list", 5)
for(i in 1:5){
    new.matrix.i[[i]] <- matrix(NA, nrow = i, ncol = i)   
}

NOTE: It is better not to create multiple objects in the global environment.注意:最好不要在全局环境中创建多个对象。 A list of matrix (or other objects) are easier and convenient to use matrix (或其他对象) list更易于使用

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

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