rloopsnested-loops

Loop models multiple times


I am trying to run the following code multiple times with different values for the 'aux' object.

time <- seq(0, 30, 1)
stock <- c(sK=0, sF=1) 
aux <- c(aH=0.4, aRel=0.5, aRes=0.5, aS=0.8)

model <- function(time, stock, aux) {
  with(as.list(c(stock, aux)), { 
    aA <- 1-sK/1  
    fH <- 1*aH*aA
    sF <- fH*aRel*0.2*0.8
    fS <- sF*aRes
    sK <- fS*aS
    net_f <- fH - fS
    net_k <- fS
    return(list(c(net_f, net_k), 
                fH=fH, fS=fS, aA=aA, net_f=net_f, net_k=net_k))
  })
}

library(deSolve)
out <- data.frame(ode(times=time, y=stock, parms=aux, func=model, method='euler'))
out

My questions are:

  1. I have created a data frame for grid search
d <- crossing(aH=seq(0, 1, 0.1), aRel=seq(0, 1, 0.1), aRes=seq(0, 1, 0.1),
              aS=seq(0, 1, 0.1))

how do I connect this grid search with the above model and get the best combination for the 'aux'? I realized that there are examples online about this issue, my problem, however, is that, 'aux' is a value of the further modeling code

out <- data.frame(ode(times=time, y=stock, parms=aux, func=model, method='euler'))
  1. For the line
sF <- fH*aRel*0.2*0.8

I need to change the value 0.2 and 0.8 to other values, for instance, 0.2 could also be change to 0.5 or 0.8, and 0.8 could also be change to 0.5 and 0.2. So for this part, there are 3*3=9 situations. What would be the correct way of doing it within the grid search?

I hope I have described my questions clearly. Please give me some advice.


Solution

  • I hope I am understanding your problem correctly. If so, my suggestion is to put the ode line inside a function that has aux as an argument. Something like

    test_aux <- function(aux) {
      data.frame(ode(times=time, y=stock, parms=aux, func=model, method='euler'))
    }
    

    Then, call this function for each line in your grid, either by using apply() or, if you want to go the dplyr way, using rowwise() and list columns:

    model_out <- apply(d, 1, test_aux)
    
    # Or
    
    library(dplyr)
    d %>%
    rowwise() %>%
    mutate(model_out = list(test_aux(c_across(aH, aRel, aRes, aS))))
    

    To select the "best combination" you should then create a function that outputs the desired metric, and iterate over model_out, again either using lapply() or sapply(), or by using mutate() to create a new column with the values of that metric.