我是一名刚开始学习 R 的数学研究生,我真的可以从任何 R 识字的人那里得到一些帮助!
我正在构建一个闪亮的应用程序来模拟概率进化行为(作为马尔可夫过程)。可以在以下位置看到(在展示模式下):
问题:应用程序的模拟部分抛出了 2 个我还没有发现的错误。它们如下:
当种群大小 N 很小(N<10)时,它经常(但不总是)抛出
Error: in sample.int(length(x), size, replace, prob) :
incorrect number of probabilities
当种群大小 N 很大(N>100)时,它经常(但不总是)抛出
Error: in sample.int(length(x), size, replace, prob) :
non-positive probability
您可以通过将人口滑块设置为最大 (200) 或最小 (0) 并重复单击“模拟单一人口”(在左侧边栏中)直到出现错误来复制此错误。在出现错误之前,您可能需要多次单击它。
问题似乎源于这部分代码:
MPM.sim <- function(t, MPM, πNought) {
# The simulation function takes as arguments: duration t, the MPM matrix of transition probabilities, and some initial condition πNought
sim <- as.numeric(t)
if (missing(πNought)) { # If the initial state is not specified
sim[1] <- (sample(1:(N+1),1) - 1) # Then take a random initial state
}else{sim[1]<-πNought} # If the initial state is specified, start from that state.
for(i in 2:t){ # For each step of the simulation after the initial state,
newstate <- sample(1:(N+1),1,prob=MPM[sim[i-1],]) # The transition to the next state is given by the transition matrix MPM.
sim[i] <- newstate
}
sim
}
我非常感谢有关如何解决此问题的任何帮助或建议!