Modelling Quokkas in R
Setting up
Declare the constants as variables
1
birthRate <- 0.1
deathRate <- 1 # i.e. 1 year
timestep <- 30
timeMax <- 10000 carryCap <-
Create a new data frame of the initial values
- A data frame is simply a table
year
,relativeCarryCap
,quokkaRate
, andquokkaRate
will be created as new columns in that table- Inspect
model
with thehead()
function
data.frame(
model <-year = 1,
relativeCarryCap = NA,
quokkaRate = NA,
quokkaPop = 5
)
head(model)
## year relativeCarryCap quokkaRate quokkaPop
## 1 1 NA NA 5
Modelling
Calculate the next timestep
For the next time step we’ll need to compute new values for year
, relativeCarryCap
, quokkaRate
, and quokkaPop
. These values will be appended as a new row (i.e. timestep) to the model
data frame.
year
takes a value of 2
2 year <-
relativeCarryCap
is the result of the previous quokka population divided by the carrying capacitymodel$quokkaPop[1]
specifies the population in the previous row (row 1) i.e. the previous time step
model$quokkaPop[1]/carryCap relativeCarryCap <-
quokkaRate
andquokkaPop
are calculated in the same fashion i.e. using the constants and values in the previous row of themodel
data frame
timestep*((1-relativeCarryCap)*birthRate*model$quokkaPop[1]-(deathRate*model$quokkaPop[1]))
quokkaRate <-
quokkaRate+model$quokkaPop[1] quokkaPop <-
- Next, we’ll create an identical data frame to
model
with our new values
data.frame(
model_temp <-year = year,
relativeCarryCap = relativeCarryCap,
quokkaRate = quokkaRate,
quokkaPop = quokkaPop
)
head(model_temp)
## year relativeCarryCap quokkaRate quokkaPop
## 1 2 5e-04 4.4975 9.4975
- We can append this time step to
model
by using therbind()
function
rbind(model,model_temp)
model <-head(model)
## year relativeCarryCap quokkaRate quokkaPop
## 1 1 NA NA 5.0000
## 2 2 5e-04 4.4975 9.4975
Speeding things up
Want to repeat that process for the next 29 time steps? Probably not. Let’s create a loop that iterates through each year, calculates the new values, and appends them to the model
data frame.
for(i in 2:timeMax){
i
year <- model$quokkaPop[i-1]/carryCap
relativeCarryCap <- timestep*((1-relativeCarryCap)*birthRate*model$quokkaPop[i-1]-(deathRate*model$quokkaPop[i-1]))
quokkaRate = quokkaRate+model$quokkaPop[i-1]
quokkaPop =
data.frame(
model_temp <-year = year,
relativeCarryCap = relativeCarryCap,
quokkaRate = quokkaRate,
quokkaPop = quokkaPop
)
rbind(model,model_temp)
model <-
}