尝试将值分配给 R 中的矩阵时出错
Error in attempting to assign values to a matrix in 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
记录1:N_trials
中每个n的destination
的结果,从而计算destination
的点估计。
但是,我遇到了错误
Error in matrix[NA, nrow = N_trials, ncol = N_steps] :
object of type 'closure' is not subsettable
我不知道这个错误是什么意思,也不知道如何解决。我想做的就是根据 destination[1]
和 destination[2]
的结果更新 directions[m][1]
和 directions[m][2]
的值。我是否错误地定义了矩阵 destinations
?
将矩阵的初始化改为matrix(NA, nrow=N_trials, ncol=N_steps)
。
这是我的完整代码:
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
的点估计。
但是,我遇到了错误
Error in matrix[NA, nrow = N_trials, ncol = N_steps] : object of type 'closure' is not subsettable
我不知道这个错误是什么意思,也不知道如何解决。我想做的就是根据 destination[1]
和 destination[2]
的结果更新 directions[m][1]
和 directions[m][2]
的值。我是否错误地定义了矩阵 destinations
?
将矩阵的初始化改为matrix(NA, nrow=N_trials, ncol=N_steps)
。