# [R] DeSolve Package and Moving Average

Eric Berger ericjberger at gmail.com
Wed Nov 29 14:49:38 CET 2017

```Since you only provide pseudo-code I will give a guess as to the source of
the problem.
It is easy to get "burned" by use of the ifelse statement. Its results have
the same "shape" as the first argument.
My suggestion is to try replacing ifelse by a standard

if ( .... ) {
} else {
}

HTH,
Eric

On Wed, Nov 29, 2017 at 1:29 PM, Werning, Jan-Philipp <
Jan-Philipp.Werning at whu.edu> wrote:

> Dear all,
>
>
> I am using the DeSolve Package to simulate a system dynamics model. At the
> problematic point in the model, I basically want to decide how many
> products shall be produced to be sold. In order to determine the amount a
> basic forecasting model of using the average of the last 12 time periods
> shall be used. My code looks like the following.
>
> “ […]
>
> # Time units in month
> START<-0; FINISH<-120; STEP<-1
>
> # Set seed for reproducability
>
>  set.seed(123)
>
> # Create time vector
> simtime  <- seq(START, FINISH, by=STEP)
>
> # Create a stock vector with initial values
> stocks   <- c([…])
>
> # Create an aux vector for the fixed aux values
> auxs    <- c([…])
>
>
> model <- function(time, stocks, auxs){
>   with(as.list(c(stocks, auxs)),{
>
> [… “lots of aux, flow, and stock functions” … ]
>
>
> aMovingAverage  <-  ifelse(exists("ResultsSimulation")=="FALSE",
> 10000,movavg(ResultsSimulation\$TotalSales, 12, type = "s”))
>
>
> return (list(c([…]))
>
>   })
> }
>
> # Call Solver, and store results in a data frame
> ResultsSimulation <-  data.frame(ode(y=stocks, times=simtime, func = model,
>                       parms=auxs, method="euler"))
>
> […]”
>
> My problem is, that the moving average (function: movavg) is only computed
> once and the same value is used in every timestep of the model. I.e. When
> running the model for the first time, 10000 is used, running it for the
> next time the total sales value of the first timestep is used. Since only
> one timestep exists, this is logical. Yet  I would expect the movavg
> function to produce a new value in each of the 120 timesteps, as it is the
> case with all other flow, stock and aux calculations as well.
>
> It would be great if you could help me with fixing this problem.
>
>
>
> Yours,
>
> Jan
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help