1

我是一名刚开始学习 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 
    }

我非常感谢有关如何解决此问题的任何帮助或建议!

4

1 回答 1

1

解决方案是:

  1. 对于偶尔在大群体中发生的错误(N>100)——转移概率的归一化项丢失了!更换它解决了这个问题。

  2. 对于小群体中偶尔发生的错误(N<10)——抽样函数中存在索引错误。我重新标记了用于采样转换概率的转换矩阵的行和列,然后(错误地)认为我可以通过它们的新名称来引用这些行。从 0 开始计数解决了这个问题。

再次感谢 @eipi10 的宝贵帮助。

于 2015-10-01T04:16:45.790 回答