Skip to content

Function in nested loop

2 messages · Eekhout, I., R. Michael Weylandt

#
Hi all,

I would like to run a function with several nested conditions, which are
completely factorial.

The input data (x1) has two different sample sizes, so:
x1 <- dat1
x1 <- dat2
Then a can have 3 different values:
a <- 0.15
a <- 0.35
a <- 0.50
Then b can have 2 different values:
b <- data.matrix (c(0.5,0.5,0.5))
b <- data.matrix (c(0.2,0.4,0.6))
Then d can have 5 different values:
d <- c (0.17,0.17,0.17)
d <- c (0.25,0.25,0.25)
d <- c (1,1,1)
d <- c (4,4,4)
d <- c (6,6,6)

In total that means that I have 60 conditions. 
I think it would be very inefficient to specify every condition
separately.
So I would like to have a nested loop where every parameter is one
nesting. 
But I don't know how to specify this exactly.
I started with the function in the loop below, where x1, a, b and d can
have multiple values and e, f, and g have only one value which is the
same of every condition:

e <- matrix(1, 3, 5, byrow = T) 
f <- data.matrix(c(0.33,0.33,0.34))
  g1 <- c(1, 2, 3, 4, 5)
  g2 <- c(9, 8, 7, 6, 5)
  g3 <- c(2, 4, 6, 8, 10)
g <- matrix(c(g1, g2, g3), 3,5, byrow = T)

n_it <- 60
for (j in 1:n_it){
  output <- function(x1=x1, a=a, b=b, d=d, e=e, f=f, g=g)
  }

Can anyone help me with this?
Thanks in advance, 

Iris
#
Without knowing the calculation you want to run, I can't give you any
more direction than this, but it sounds like you need to take a step
back and rethink your problem in terms of vectorization. If you can do
so, outer() might be able to help as well as direct vectorwise
calculation.

If it's entirely impossible to vectorize, how about putting all the
different options in lists and looping over those? (Though I can't
believe I just suggested 5 nested loops in R! the shame...)

Michael
On Tue, Oct 18, 2011 at 3:28 AM, Eekhout, I. <i.eekhout at vumc.nl> wrote: