Here's my shot at it. The gouter function can be enhanced further (e.g., as
outer() does with dimnames), but I think the basic functionality is there.
You can basically pass in any number of vectors you want, but you need to
wrap them in a single list. outer() allows arrays, but gouter() below will
only work with list of vectors.
gouter <- function(x, FUN, ...) {
xgrid <- as.list(do.call("expand.grid", x))
names(xgrid) <- NULL
xdim <- sapply(x, length)
array(do.call(deparse(substitute(FUN)), c(xgrid, list(...))),
dim=sapply(x, length), dimnames=x)
}
Here's a simple test:
f <- function(x, y, z) x + y + z
x1 <- 1:3
x2 <- 4:5
x3 <- 6:9
gouter(list(x1, x2, x3), f)
From: Wolfgang Viechtbauer
Hello,
outer() is great for avoiding things like:
for (val1 in val1s) {
for (val2 in val2s)) {
x[i,j] <- somefunction(val1, val2)
}
}
The same can be obtained with:
outer(val1s, val2s, somefunction)
But what if there are three (or more) sets of values to loop over? Any
way of avoiding the loops then?
Thanks,
--
Wolfgang Viechtbauer
------------------------------------------------------------------------------
Notice: This e-mail message, together with any attachments,...{{dropped}}