在嵌套的 for 循环之外的何处初始化矩阵是否重要?

Does it matter where I initialize my matrix outside my nested for-loops?

我有以下 R 代码。我想知道我放的时候有什么区别 函数外的 mat<-matrix(1:20, ncol=5) 。我在这两种情况下都得到了相同的结果。

fun<-function(x,y){
  mat<-matrix(1:20, ncol=5)
  for (i in 1:x){
    for (j in 1:y){
      mat[i,j]=rnorm(1)
      return(mat)
    }
  }
}
fun(4,5)

以下代码按照评论和答案中的建议工作。为什么像上面那样转换成函数就不行了?

mat<-matrix(1:20, ncol=5)
for(i in 1:4){
  for (j in 1:5){
   mat[i,j]=rnorm(1)
  }
}
mat
fun1 <- function(x,y) {
  mat <- matrix(1:20, ncol=5)
  mat[1:x, 1:y] <- rnorm(x*y)
  mat
}

这将实现您的目标,即创建一个接受索引作为两个参数的函数和 returns 一个矩阵,该矩阵具有按索引随机正态分布的数字。

fun1(2,1)
#           [,1] [,2] [,3] [,4] [,5]
#[1,] -0.2883407    5    9   13   17
#[2,] -0.5290704    6   10   14   18
#[3,]  3.0000000    7   11   15   19
#[4,]  4.0000000    8   12   16   20

注意函数调用时返回最后一行。

函数中创建的 mat 矩阵在全局环境中不可用:

mat
#Error: object 'mat' not found

每当您作为 R 的新用户编写嵌套 for 循环时,都应该敲响警钟。通常有更好的方法。嵌套循环的好处是 "makes sense." 但是逻辑清晰的层层递进,执行起来效率很低。当然也有例外,但您很可能不会很快 运行 加入其中。最好花时间学习 R 的编程直觉。

有很多关于研究范围的讨论:

  1. R environments and function call stacks

  2. Scoping and functions in R 2.11.1 : What's going wrong?

  3. http://developer.r-project.org/nonstandard-eval.pdf

  4. http://adv-r.had.co.nz/Functions.html#lexical-scoping