Skip to Content

writing a loop in R - new to R and really struggling to understand

I have this basic stage-structured life-cycle model (below) and am trying to figure out how to run this for different temperatures - 0 - 20 in increments of 2 - without have to run the model several times. I then want to be able to plot the 'arrival time of individuals into last class' i.e. plot(temp,arrival time)....

nclass <- 100        # number of classes
nsteps <- 1000       # number of model steps
n0 <- 100            # number of individuals
n <- rep(0, nclass)  # number of individuals in classes 0 to nclass
p <- 0.5             # proportion of individuals that move into next class
tau0 <- 120          # time (in days) taken to reach last class at temp=8 degC
Tc <- 8              # characteristic temp
temp <- 8            # temperature (deg C)
 
n[1] <- n0
m <- n
time <- 0
for (i in 1:nsteps) {
    j <- nclass
    n[j] <- n[j] + p*n[j-1]
    for (j in (nclass-1):2) {
        n[j] <- (1-p)*n[j]+p*n[j-1]
    }
    j <- 1
    n[j] <- (1-p)*n[j]
    m <- rbind(m, n)
    tau <- (tau0 * exp(-temp/Tc)/nclass)/p
    time <- c(time, time[i]+tau)
}
 
# I'm not sure how to implement this...I have tried to add in another loop:
result <- rep(0,11)
for(j in 1:11){
    temp <- (j-1)*2
 
    [RUN MODEL HERE]
 
    result[j] <- arrival time
}

I was given that little extra bit by my supervisor but still don't understand how to fit it in. It may be that that's not exactly what it should be but I've tried a variety of things and can't get it to work.

If anyone can shed some light I'd be really grateful.