Re: [R] Error using outer

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Tue 03 Oct 2006 - 14:03:53 GMT

"Alberto Monteiro" <albmont@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@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@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 and provide commented, minimal, self-contained, reproducible code. Received on Wed Oct 04 00:08:42 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 03 Oct 2006 - 14:30:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.