[R] Error using outer

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Oct 3 16:03:53 CEST 2006


"Alberto Monteiro" <albmont at centroin.com.br> writes:

> Why is this an error?
> 
>   mat <- matrix(1:64, 8, 8)
>   x <- y <- 1:8
>   z <- outer(x, y, function(x, y) mat[x,y])
> 
> when this is not an error:
> 
>   mat <- matrix(1:64, 8, 8)
>   x <- y <- 1:8
>   z <- outer(x, y, function(x, y) paste("mat[", x, ",", y, "]", sep=""))

Because, outer vectorizes, and e.g., 

mat[1:2,1:2] has *four* elements, 

whereas paste("mat[", 1:2, ",", 1:2, "]", sep="") has only two.

So mat[x,y] will be 64x64 ad dimensions don't fit.

It works if you use the matrix index:

> z <- outer(x, y, function(x, y) mat[cbind(x,y)])
> z
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    9   17   25   33   41   49   57
[2,]    2   10   18   26   34   42   50   58
[3,]    3   11   19   27   35   43   51   59
[4,]    4   12   20   28   36   44   52   60
[5,]    5   13   21   29   37   45   53   61
[6,]    6   14   22   30   38   46   54   62
[7,]    7   15   23   31   39   47   55   63
[8,]    8   16   24   32   40   48   56   64


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list