Search code examples
rdifferential-equationscalculus

How to solve and plot differential equations in R


Taken from Sal Khan's lecture https://www.youtube.com/watch?v=oiDvNs15tkE of the Khan academy, if I know that dN/dt=rN(1-(N/K)) (the logistic differential equation)

How can I solve for N and plot the N=f(t) with R?

Thanks


Solution

  • This logistic equation has an analytical solution (see for example here), so you can plot it directly. Another option is to solve it numerically using one of the available solvers (see here)

    ## Using the `deSolve` package
    library(deSolve)
    
    ## Time
    t <- seq(0, 100, 1)
    
    ## Initial population
    N0 <- 10
    
    ## Parameter values
    params <- list(r=0.1, K=1000)
    
    ## The logistic equation
    fn <- function(t, N, params) with(params, list(r * N * (1 - N / K)))
    
    ## Solving and plotin the solution numerically
    out <- ode(N0, t, fn, params)
    plot(out, lwd=2, main="Logistic equation\nr=0.1, K=1000, N0=10")
    
    ## Ploting the analytical solution
    with(params, lines(t, K * N0 * exp(r * t) / (K + N0 * (exp(r * t) - 1)), col=2, lwd=2))
    

    enter image description here