how to write a loop of the number of for loops in R? -
this simple one, somehow got stuck...
i need many loops result of every sample in support usual stacked loops:
for (a in 1:n1){ (b in 1:n2){ (c in 1:n3){ ... } } }
but number of loops needed in messy system depends on random variable, let's say, for(f in 1:n.for)
so how can write loop deal this? or there more elegant ways this?
note difference nested loops above (the variables a,b,c,...) matter in calculations, variable f of loop controls number of loops needed not go of calculations real purpose - count/ensure number of loops needed correct.
did make clear?
so trying generate possible combinations of number of peoples preferences towards others.
let's have 6 people (the simplest case purpose): abi, bob, cath, dan, eva, fay.
abi , bob have preference lists of c d e f ( 4!=24 possible permutations each of them);
cath , dan have preference lists of b , e f, respectively (2! * 2! = 4 possible permutations each of them);
eva , fay have preference lists of b c d (4!=24 possible permutations each of them);
so there should 24*24*4*4*24*24 possible permutations of preferences when taking 6 them together.
i wondering clear, easy , systematic way generate them @ once?
i'd want them in format such as
c.prefs <- as.matrix(data.frame(abi = c("eva", "fay", "dan", "cath"),bob = c("dan", "eva", "fay", "cath"))
but clear format fine...
thank much!!
i'll assume have list of each loop variable , maximum value, ordered outermost innermost variable.
loops <- list(a=2, b=3, c=2)
you create data frame loop variable values in correct order with:
(indices <- rev(do.call(expand.grid, lapply(rev(loops), seq_len)))) # b c # 1 1 1 1 # 2 1 1 2 # 3 1 2 1 # 4 1 2 2 # 5 1 3 1 # 6 1 3 2 # 7 2 1 1 # 8 2 1 2 # 9 2 2 1 # 10 2 2 2 # 11 2 3 1 # 12 2 3 2
if code run @ innermost point of nested loop doesn't depend on previous iterations, use apply
process each iteration independently. otherwise loop through rows of data frame single loop:
for (i in seq_len(nrow(indices))) { # can "a" indices$a[i], "b" indices$b[i], etc. }
Comments
Post a Comment