[R] Problem with "outer" function
Robin Hankin
rksh at soc.soton.ac.uk
Thu Oct 28 16:22:28 CEST 2004
Hi
you need expand.grid():
aa <- c(1,2)
> bb <- c(3,4)
> cc <- c(5,6)
> expand.grid(aa,bb,cc)
Var1 Var2 Var3
1 1 3 5
2 2 3 5
3 1 4 5
4 2 4 5
5 1 3 6
6 2 3 6
7 1 4 6
8 2 4 6
#define a toy function (here just a max() but you can make
# this function anything you like:
> f <- function(x){max(x[1] , x[2] ,x[3])}
#then just apply() the toy function f():
> apply(expand.grid(aa,bb,cc),1,f)
1 2 3 4 5 6 7 8
5 5 5 5 6 6 6 6
HTH
rksh
>,
>
>I am having a problem with the "outer" function.
>
>I am using R 1.9.1 on Windows 2000. My problem may be described as follows:
>
>I have a function f of 3 variables and 3 vectors, aa, bb and cc. I would like
>to evaluate this function in a 3-dimensional grid of points corresponding to
>all combinations of the elements of the 3 vectors. For example, if
>
>aa<-c(1,2)
>bb<-c(3,4)
>cc<-c(5,6)
>
>then I'd like a loop which evaluates the 2^3 values f(1,3,5), f(1,3,6),
>f(1,4,5), f(1,4,6),f(2,3,5),f(2,3,6),f(2,4,5) and f(2,4,6).
>
>The easy way to do this would be to nest 3 for-next loops, but I hope that I
>more elegant way is possible, especially because in the actual problem at hand
>I need to make such evaluations with a function of n parameters. I was hoping
>to create a 3-dimensional array consisting of 3-element vectors, and then be
>able to use a single loop to get through all the values. I expected to do this
>with
>
>outer(outer(aa,bb,c),cc,c)
>
>However, I get the following error when I use the "outer" function with the
>concatenate function "c" as the third argument:
>
>>outer(aa,bb,c)
>Error in outer(aa,bb,c) : dim<- : dims [product 4] do not match the length of
>object [8]
>
>Does anyone know a way to get around this? I have consulted the R manuals
>without results, and I can't seem to find the problem described in the mail
>archives either.
>
>Thanks,
> Alexander
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
--
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
SO14 3ZH
tel +44(0)23-8059-7743
initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)
More information about the R-help
mailing list