# [R] Outer with Three Vectors

Liaw, Andy andy_liaw at merck.com
Fri Feb 27 03:53:36 CET 2004

```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)
, , 6

4  5
1 11 12
2 12 13
3 13 14

, , 7

4  5
1 12 13
2 13 14
3 14 15

, , 8

4  5
1 13 14
2 14 15
3 15 16

, , 9

4  5
1 14 15
2 15 16
3 16 17

HTH,
Andy

> 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help