Variable number of for loops in R
r
Solution
No need to use loops
f <- function(vec, fn){
vecs <- mapply(seq, 0, vec)
tmp <- do.call(expand.grid, vecs)
tmp <- apply(tmp, 1, fn)
sum(tmp)
}
fn = function(x){sum(x^2)}
f(c(3, 4, 6, 5), fn = fn)
Problem
I'm working in R and would like to pass a vector to a function. The vector gives the maximum values for a series of for loops. If the vector is (3,4,6,5), then the following code should be run. So the number of for loops depends on the length of the vector that is passed to the function. Then for each possibility, the counters are input into another function fn. Provided an example for a possible fn below. ``` S=0 fn = function(x){sum(x^2)} for (i in 0:3){ for (j in 0:4){ for (k in 0:6){ for (l in 0:5){ S=S+fn(c(i,j,k,l)) } } } } ``` I believe recursion is the way to go here, but I haven't had any luck figuring it out, and most of the recursion examples I've seen seem to be at a very high or very low level. Any idea what the best way to approach this problem is?