简体   繁体   中英

R: Can a matrix be populated in a loop by indexing both rows and columns?

I am a biologist and an R newbie, and I'm learning how to create a simple population model.

So, I have a population matrix ("pop")of 30 age classes of female (1:4 are non-breeders, 5:30 are breeders) which will be modelled for 100 years.

pop <- matrix(0,30,100)

I then populate this matrix with 3 young adult females.

pop[5, 1] <- 3

I then want to run this for 100 years, with stochasticity, to see how this population does over time. (I haven't filled these in but you don't need them, they all have different survival probabilities to the sexually-mature adults.)

for (t in 1:100)  {  # Edited y to t, typing error!
    pop[1,t+1] <- rbinom(1,colSums(pop[5:30, t]), b/2) 
    pop[5, t+1] <- rbinom(1, pop[4, t], s2)
    pop[6, t+1] <- rbinom(1, pop[5, t], s2)
    .....
    pop[30, t+1] <- rbinom(1, pop[29, t], s2)
}

So my question is: is there any way of populating this matrix without having to explicitly write 30 lines of code? Because lines 5 - 30 are all going to be the same, and yet even after 5 hours (literally) of web searching and R manual reading I can't find a way to index the rows, which seems to be what's needed here.

Any insight is welcome here, including a different way of modelling this population.

since rbinom is vectorized, you should be able to replace

pop[1,t+1] <- rbinom(1,colSums(pop[5:30, t]), b/2) 
pop[5, t+1] <- rbinom(1, pop[4, t], s2)
pop[6, t+1] <- rbinom(1, pop[5, t], s2)
.....
pop[30, t+1] <- rbinom(1, pop[29, t], s2)

with

pop[,t+1] <- rbinom(27,size=c(colSums(pop[5:30,t]),pop[4:29,t]),
                       prob=c(b/2,rep(s2,26)))

or something like that (the 26 and 27 may be wrong, I may have miscounted)

However, what I really think you should do is something like this:

pop[1,t+1]  <- rpois(1,b/2*sum(pop[5:30,t]))
pop[-1,t+1] <- rbinom(29,size=pop[1:29,t]),
                       prob=c(rep(s1,4),rep(s2,26)))

This assumes that individuals in the last age class fall off the edge of the world and die ... I'm using rpois here to allow Poisson reproduction rather than binomial, although you could use rbinom(1,size=sum(pop[5:30,t])/2,prob=p) if you really want to insist that females have at most 1 offspring (with probability p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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