我是一名刚刚开始学习R的数学研究生,我真的需要任何懂R的人的帮助!
我正在构建一个闪亮的应用程序,模拟概率进化行为(作为一个马尔可夫过程)。可以看到(在展示模式下)在:
- https://amohseni.shinyapps.io/Moran-Process
问题:应用程序的模拟部分抛出了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
您可以通过将人口滑块设置为max(200)或min(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
}
我非常感谢任何关于如何解决这个问题的帮助或建议! 解决方案如下:
-
对于偶尔发生在大种群(N>100)中的错误,一个转换概率的归一化项丢失了!
-
对于偶尔发生在小群体中的误差(N<10),抽样函数中存在索引误差。我重新标记了用于采样转移概率的转移矩阵的行和列,然后(错误地)认为我可以用它们的新名称来引用这些行。
再次感谢@eipi10的宝贵帮助。