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

Toby Muhlhofer toby.m at mail.utexas.edu
Wed Sep 20 22:00:16 CEST 2006


It just seemed wierd because over a 2d array, it also returns vectors, 
but I guess breaking things down into components of the list it makes 
sense. Besides, using David's suggestion of apply(at, MARGIN, I) also 
offers the insights I need.

Gabor Grothendieck wrote:
> Read ?apply carefullly.    If FUN returns as a scalar as it does here
> then the result dimensions are dim(X)[MARGIN]. For example,
> 
> apply(X, 1, max) has three components which are
> max(X[1,,]), max(X[2,,]) and max(X[3,,])
> 
> and apply(X, 3, max) has three components which are
> max(X[,,1]), max(X[,,2]) and max(X[,,3])
> 
> Also try apply(X, 1:2, max), etc.
> 
> On 9/20/06, Toby Muhlhofer <toby.m at mail.utexas.edu> wrote:
>> 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
>>
>> ______________________________________________
>> 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
>> and provide commented, minimal, self-contained, reproducible code.
>>
>



More information about the R-help mailing list