adaml768
adaml768

Reputation: 29

replacing nested for loop with sapply in R

So I have 10 parameters, with 7 fixed and 3 varying using seq. Each varying parameter has 10 possibilities. Right now I create an empty data frame and fill it after going through a bunch of functions and generating an output for each combination of parameters. So there is 1000 (10*10*10) possibilities. Right now I use nested for loops. Lets say m,g, and x are my varying parameters. Here is an example.

m.c <- seq(1,10, by=1)  
m.i <- seq(1,10, by=1) * 0.5
a <-  .5 
b <-  1
c <-  .5
gg <-  seq(.02,.2, by=.02)
n <-  7
r <-  .25
alpha <-  2
dt <-  1
X <-  seq(.01,.1, by=.01)
intervention.data <-  data.frame(intervention = numeric())
parameter.data <-  data.frame(m=numeric(), g=numeric(), X=numeric())

A.c = function(m = m.c,a,b,c,g,n,r,alpha,dt,X) { 
    1 - exp(-dt*(1/(alpha*dt)*log(1+(alpha*b*dt*m*a^2*c*X*exp(-g*n))/(a*c*X+g))))
}

A.i = function(m = m.i,a,b,c,g,n,r,alpha,dt,X) { 
    1 - exp(-dt*(1/(alpha*dt)*log(1+(alpha*b*dt*m*a^2*c*X*exp(-g*n))/(a*c*X+g))))
}

for (i in 1:length(mm)) {
  m = mm[i]

  for (ii in 1:length(gg)) {
    g = gg[ii]

    for (iii in 1:length(XX)) { 
      X = XX[iii]

      parameter.data = rbind(parameter.data, data.frame(m=m, g=g, X=X))

      a.c = A.c(m = m.c,a,b,c,g,n,r,alpha,dt,X)
      a.i = A.i(m = m.i,a,b,c,g,n,r,alpha,dt,X)

      intervention.effect= a.i/a.c

      intervention.data = rbind(intervention.data, data.frame( intervention = intervention.effect))
    }
  }
}

all.intervention.data = cbind(parameter.data, intervention.data)  

What I have works but seems pretty inefficient so I have been trying to find how to use sapply or lapply but have not been successful in understanding to use them so all the combos. are made. Any help is appreciated.

Upvotes: 0

Views: 163

Answers (1)

Chris
Chris

Reputation: 6372

You seem to have lost mm in your data, so I can not follow perfectly, but a better way to do this would be to vectorize:

all.data <- expand.grid(m.c = m.c,gg = gg,X = X)
all.data$m.i <- all.data$m.c * 0.5

all.data$a.c <- A.c(m = all.data$m.c,a,b,c,all.data$gg,n,r,alpha,dt,all.data$X)
all.data$a.i <- A.i(m = all.data$m.i,a,b,c,all.data$gg,n,r,alpha,dt,all.data$X)

Upvotes: 2

Related Questions