[R] Unexpected behavior of apply() over a 3d array

Toby Muhlhofer toby.m at mail.utexas.edu
Wed Sep 20 21:35:50 CEST 2006


Dear listeRs,

I'm finding that apply() behaves strangely when used on a 3-d array. For 
example:

 > at <- array(1:27,dim=c(3,3,3))
 > at
, , 1

      [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2

      [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18

, , 3

      [,1] [,2] [,3]
[1,]   19   22   25
[2,]   20   23   26
[3,]   21   24   27

 > apply(at, 1, max)
[1] 25 26 27

If, for the MARGIN argument in apply() 1 is rows, I would have expected 
as output a 3x3 matrix something like

7 16 25
8 17 16
9 18 27

Either that, or maybe the transpose of that, but a single vector seems 
rather random. Especially when you go

 > apply(at, 3, max)
[1]  9 18 27

What is that the max of? Each submatrix? The diagonal? I'm confused. Can 
anyone clarify this?

Besides this, is there a function that will work on a 3d array, the way 
I'm implying, or do I need to write an explicit loop that takes 2d 
slices of my 3d array?

Thanks!

	Toby



More information about the R-help mailing list