首页 > 解决方案 > 尝试将值分配给 R 中的矩阵时出错

问题描述

这是我的完整代码:


N_trials <- 1000
N_steps <- 1000
destinations <- matrix[NA, nrow=N_trials, ncol=N_steps]
l1_distance <- numeric(N)


for(m in 1:N_trials) {
  destination <- c(0,0)
  for(n in 1:N_steps) {
    if(runif(1) < 1/4) {
      destination[1] <- destination[1] - 1
    }
    else if(runif(1) < 1/2) {
      dstination[1] <- destination[1] + 1
    }
    else if(runif(1) < 3/4) {
      dstination[2] <- destination[2] + 1
    }
    else if(runif(1) < 1) {
      dstination[2] <- destination[2] - 1
    }
  }
  destinations[[m,1]] <- destination[1]
  destinations[[m,2]] <- destination[2]


l1_distance <- abs(destinations[N_trials][1]) + abs(destinations[N_trials][2])

}

print(mean(l1_distance))

本质上,destination是一个从 (0,0) 开始并以 1/4 的概率移动到相邻正方形(在 l^1 度量中)进行N_steps迭代的向量。destinations记录 中destination每个 n的结果1:N_trials,从而计算 的点估计destination

但是,我遇到了错误

矩阵 [NA, nrow = N_trials, ncol = N_steps] 中的错误:“闭包”类型的对象不是子集

我不知道这个错误是什么意思或如何解决它。我要做的就是根据 and 的结果更新and的directions[m][1]值。我是否错误地定义了矩阵?directions[m][2]destination[1]destination[2]destinations

标签: rmatrixsimulation

解决方案


将矩阵的初始化更改为matrix(NA, nrow=N_trials, ncol=N_steps)


推荐阅读