【问题标题】:Create multiple matrices in one for loop在一个 for 循环中创建多个矩阵
【发布时间】:2017-11-22 00:24:07
【问题描述】:

我是 R 新手,目前正在学习创建 for 循环。

我想要做的是创建 6 个具有类似结构的矩阵(唯一的区别是行“a”随矩阵的数量而变化):

matrix1<- matrix(nrow=5, ncol=5, dimnames= list(c("a", "b", "c", "d", "e")

for(i in 1:5){
matrix1[1,]= 1
matrix1[2,]= round(rpois(5,1), digits=0)
matrix1[3,]= round(rpois(5,1), digits= 0)
matrix1[4,]= round(rnorm(5, 50, 25), digits= 0)
matrix1[5,]= round(rnorm(5, 50, 25), digits= 0)
}

有没有使用 for 循环而不是单独执行此操作的有效方法?

我也考虑过创建 6 个 5*5 的矩阵,填充 NA 值,然后用所需的值填充这些矩阵,但我不知道该怎么做。

如果你能帮助我,那就太好了! 谢谢!

【问题讨论】:

  • 写一个x的函数做矩阵,然后做lapply(values_for_x, fun)?请注意,最好有一个矩阵列表,而不是在 matrix1matrix2、...等名称中嵌入矩阵编号。
  • 但是这个函数怎么写呢?能给我举个例子吗?
  • fun &lt;- function(x){ your_code_here_over_multiple_lines } 在花括号内,您可以像上面那样编写代码,确保它使用函数参数(x 或任何您想调用的)来生成“a”行不同,如你所愿。

标签: r for-loop matrix dataframe


【解决方案1】:

不需要 for 循环,您的代码无需它即可运行。在 R 中,for 循环允许您使用一个临时对象,该对象在每个循环中从 1 到 5 进行 1 次迭代(在您的情况下)。为了利用循环,您需要使用i。您当前的 for 循环实际上只是将自身覆盖了 5 次。

这是一个在列表中创建 6 个矩阵的循环。这里的诀窍是我使用i 不仅在列表中创建一个新元素(矩阵),而且还设置第一行随着它的数字矩阵而变化。

# First it is good to initialize an object that you will iterate over
lists <- vector("list", 6) # initialize to save time

for(i in 1:6){
  # create a new matrix and set all values in it to be i
  lists[[i]] <- matrix(i, nrow = 5, ncol = 5, dimnames= list(c("a", "b", "c", "d", "e")
))
  # change the remaining rows
  lists[[i]]["b",] <- round(rpois(5,1), digits = 0)
  lists[[i]]["c",] <- round(rpois(5,1), digits = 0)
  lists[[i]]["d",] <- round(rnorm(5, 50, 25), digits= 0)
  lists[[i]]["e",] <- round(rnorm(5, 50, 25), digits= 0)
}

# Properly name your lists
names(lists) <- paste0("Matrix",1:6)

# Now you can call the lists individually with
lists$Matrix1

# Or send them all to your environment with
list2env(lists, env = .GlobalEnv)

如果这有帮助,或者如果您还有其他问题,请告诉我~

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多