【发布时间】:2019-12-22 13:39:42
【问题描述】:
这是我的完整代码:
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) 开始的向量,并且在 N_steps 迭代中以 1/4 的概率移动到相邻的正方形(在 l^1 度量中)。 destinations记录destination对1:N_trials中每个n的结果,从而计算destination的点估计。
但是,我遇到了错误
矩阵中的错误[NA, nrow = N_trials, ncol = N_steps] : “闭包”类型的对象不是子集
我不知道这个错误是什么意思或如何解决它。我要做的就是根据destination[1] 和destination[2] 的结果更新directions[m][1] 和directions[m][2] 的值。我是否错误地定义了矩阵destinations?
【问题讨论】:
标签: r matrix simulation