【问题标题】:Using for loop counter to identify matrix in R使用 for 循环计数器识别 R 中的矩阵
【发布时间】:2017-06-02 23:42:14
【问题描述】:

我正在运行一些 OLS 估计的蒙特卡罗模拟,其中我针对不同的 beta 值进行了多个版本的相同模拟。为此,我设置了一个 for 循环来运行模拟(有 1000 次重复),并围绕它包裹了第二个循环,我想在其中分配 beta 值。

所以,我设置了 4 个矩阵来存储每个版本的模拟结果,我想使用 for 循环计数器确定要写入哪个矩阵。

这是我的设置的一个简单示例:

reps = 1000
mat1 = matrix(NA, nrow=reps, ncol=2)
mat2 = matrix(NA, nrow=reps, ncol=2)
mat3 = matrix(NA, nrow=reps, ncol=2)
mat4 = matrix(NA, nrow=reps, ncol=2)

for(i in 1:4){
    #Here I am going to alter my beta values for each iteration of i
    for(j in 1:reps){
        #Here I run my simulation and store values to mat1, mat2, mat3, mat4
        #I want to store to mat1 on first iteration of j, mat2 on second etc.
        model <- lm(Y~X)
        mat[["i"]][j,1] <- model$coef[1]
        mat[["i"]][j,2] <- model$coef[2]
    }
}

对于 i 循环的第 1 次迭代,我希望 mat[["i"]][j,1] 与 mat1 的第 1 列、第 2 次迭代与 mat2 等相关联。这显然不起作用,因为我在这里对其进行了编码我不知道如何使它工作。

我可以通过关于 i 值的 if else 语句来实现这一点,但如果可能的话,我想避免这种情况。

编辑

感谢大家的帮助!这有效:

reps = 1000
myMatList <- list()

for(i in 1:4){
    #Here I am going to alter my beta values for each iteration of i

    myMatList[[i]] <- matrix(NA, nrow=reps, ncol=2)

    for(j in 1:reps){
        #Here I run my simulation and store values to mat1, mat2, mat3, mat4
        #I want to store to mat1 on first iteration of j, mat2 on second etc.
        model <- lm(Y~X)
        myMatList[[i]][j,1] <- model$coef[1]
        myMatList[[i]][j,2] <- model$coef[2]
    }
}

【问题讨论】:

  • 将矩阵存储在一个列表中:myMatList &lt;- mget(ls(pattern="mat\\d+")) 然后引用它们。有关详细信息,请参阅this post。它讨论了 data.frames,但概念是相同的。
  • 这对你有用吗do.call(rbind,lapply(1:4000,function(x) { data.frame(iter = x, t(coefficients(lm(Y~ X, data=mtcars)))) }))

标签: r for-loop matrix


【解决方案1】:

我不确定您的代码是否不起作用,但我认为这可能会有所帮助:

l <- list()
reps = 10

for(i in 1:4) {
  l[[i]] <- matrix(NA, nrow=reps, ncol=2)
}
l[[1]][1, 1] # [1] NA
l[[1]][1, ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多