Differential equations
We need to solve a system of ordinary differential equations (ODEs) and choose to use the classical Runge–Kutta fourth-order integration function rk4 from the odesolve package:
install.packages("odesolve") library(odesolve)
The example involves a simple resource-limited plant herbivore where V = vegetation and N = herbivore population. We need to specify two differential equations: one for the vegetation (dV/dt) and one for the herbivore population (dN/dt):
The steps involved in solving these ODEs in R are as follows:
- Define a function (called phmodel in this case).
- Name the response variables V and N from x[1] and x[2].
- Write the vegetation equation as dv using with.
- Write the herbivore equation as dn using with.
- Combine these vectors into a list called res.
- Generate a time series over which to solve the equations.
- Here, t is from 0 to 500 in steps of 1.
- Set the parameter values in parms.
- Set the starting values for V and N in y and xstart.
- Use rk4 to create a dataframe with the V and N time series.
phmodel <-function(t, x, parms) { v<-x[1] n<-x[2] with(as.list(parms), { dv<-r*v*(K-v)/K - b*v*n dn<-c*v*n – d*n res<-c(dv, dn)
list(res) })} times <-seq(0, ...
Get The R Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.