简体   繁体   English

在R中无限运行嵌套for和while循环的问题

[英]Having issues with infinitely running nested for and while loops in R

I'm trying to model a population where each year the population is either growing quickly or slowly, to a max size of 5000. I then am running this while loop 5000 times to look at variation in time to 5000. 我正在尝试模拟一个人口,该人口每年快速增长或缓慢增长,最大规模为5000。然后在运行5000次的同时运行此循环,以查看5000的时间变化。

However, the loop just keeps running, and I have to stop it manually. 但是,循环一直保持运行状态,我必须手动停止它。

One odd thing is that popVector , which is a vector that records the size of the population each round, grows to a tremendous size, often into the tens of thousands, which I would not predict from the numbers I'm using. 一件奇怪的事是popVector ,它是记录每个回合人口规模的向量,它会增长到巨大的大小,通常成千上万,我无法根据我使用的数字进行预测。

Any help to resolve this would be greatly appreciated! 任何解决此问题的帮助将不胜感激!

MAXPOP <- 5000 #Set max population
trials <- 5000
genVector <- numeric(trials)
set.seed(1)

for(j in 1:trials) {
  curr_pop <- 20 #Set initial population
  genTime <- 1
  popVector <- curr_pop;
  while(curr_pop <= MAXPOP) {
    if(genTime%%2 == 0) {
      p <- 0.25
    }
    if(genTime%%2 != 0) {
      p <- 0.5
    }
    curr_pop <- sum(rgeom(curr_pop, p)) #Set current population
    popVector <- c(popVector, curr_pop)
    genTime <- genTime + 1
  }
  genVector[j] <- genTime
}

The issue appears to be in your while loop. 问题似乎出在您的while循环中。 When I run the code curr_pop gets sets to zero on the 2826 iteration of your for loop. 当我运行代码时,curr_pop在for循环的2826迭代中被设置为零。 I"m not familiar enough with the rgeom function, but that's the place to investigate what would cause it to return a zero. 我对rgeom函数还不太熟悉,但这是研究导致它返回零的原因的地方。

The rgeom function returns a vector of random numbers, with as many elements as the first argument. rgeom函数返回一个随机数向量,该向量具有与第一个参数一样多的元素。 With a small first argument, and a second argument close to 1, it is a matter of time before it returns a set of all zeros, after which your curr_pop <- sum(rgeom(curr_pop, p)) will remain 0 forever. 在第一个参数较小且第二个参数接近1的情况下,返回一组全零是时间问题,之后curr_pop <- sum(rgeom(curr_pop, p))永远保持0。

You could work around that by wrapping that call in a while loop to check for 0 sum and resetting curr_pop to something else, for example: 您可以通过在while循环中包装该调用以检查0和并将curr_pop重置为其他方式来解决此问题,例如:

while (T) {
    curr_pop <- sum(rgeom(curr_pop, p)) #Set current population
    if (curr_pop > 0) break
    else curr_pop <- 1
}

The iteration step 2826 mentioned by @Havik23 is because of the set.seed(1) call. @ Havik23提到的迭代步骤2826是由于set.seed(1)调用引起的。 This way always the same sequence of random numbers will be generated. 这样,将始终生成相同的随机数序列。 If you want your program to be more random , you might want to comment out that call. 如果您希望程序更加随机 ,则可能需要注释掉该调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM