How to include an R object within the body of a function


#1

Hello ...
I would like to create a function for integrating and plotting ODEs. Like the function below, the equations are entered directly into the body of the function. Is there however a way that the equations can be entered as objects outside the function then within the function, we simply enter the object name for each of the equations.

library(deSolve)
eqtns = function (t,x,params){
_ _
_ # state variables_
_ S = x[1]_
_ I = x[2]_
_ R = x[3]_
_ # parameters_
_ _
_ beta = params["beta"]_
_ gamma = params["gamma"]_
_ _
_ # model equations_
_ dSdt = -beta * S * I_
_ dIdt = beta * S * I - gamma * I_
_ dRdt = gamma * I_
_ _
_ # combine into a single vector_
_ dxdt = c(dSdt,dIdt,dRdt)_
_ _
_ # return result as a list_
_ list(dxdt)_
}

I want to do it this way because my intention is to allow users to enter the three equations in a text field of my R Shiny app as a vector say: Eqtns = c("-beta * S * I", "beta * S * I - gamma * I", "gamma * I"), then reference them using Eqtns[i], i = 1,2,3. I thought the code below could work but it doesn't.

library(deSolve)
eqtns = function (t,x,params){
_ _
_ # state variables_
_ S = x[1]_
_ I = x[2]_
_ R = x[3]_
_ # parameters_
_ _
_ beta = params["beta"]_
_ gamma = params["gamma"]_
_ _
_ #shiny model equations_
_ dSdt = Eqtns[1]
_ dIdt = Eqtns[2]
_ dRdt = Eqtns[3]
_ _
_ # combine into a single vector_
_ dxdt = c(dSdt,dIdt,dRdt)_
_ _
_ # return result as a list_
_ list(dxdt)_
}

My question is therefore: Is there a way an R object(created outside the function) can be included in the body an R function by simply calling its object name?

Thank you.