这是我的完整代码:
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
记录1:N_trials
中每个n的destination
结果,从而计算destination
的点估计。
但是,我遇到了错误
矩阵中的错误[NA, nrow = N_trials, ncol = N_steps] : 类型为"闭包"的对象不可子集化
我不知道此错误是什么意思或如何解决它。我想做的是根据destination[1]
和destination[2]
的结果更新directions[m][1]
和directions[m][2]
的值。我是否正确定义矩阵destinations
?
将矩阵的初始化更改为matrix(NA, nrow=N_trials, ncol=N_steps)
。