[R] curious about dimension of 'apply' output when MARGIN=1

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jan 18 09:42:23 CET 2007


On Wed, 17 Jan 2007, Patrick Burns wrote:

> A logical reason for the phenomenon is that
> matrices are stored down their columns. For
> example:
>
> > matrix(1:15,5)
>     [,1] [,2] [,3]
> [1,]    1    6   11
> [2,]    2    7   12
> [3,]    3    8   13
> [4,]    4    9   14
> [5,]    5   10   15
>
> When an 'apply' across rows is done, it will be
> the values corresponding to each of the rows that
> are together.
>
> For matrices, merely transposing the result fixes
> the "problem", but it is considerably more complex
> in higher dimensional arrays.

[I don't think so, using aperm.]

> There could be a spectrum of opinion from:
>
> the original programmer was lazy and didn't adequately
> serve users
>
> to:
>
> the simpler the program the fewer bugs there will be.

Or that the vision of the original designer was not limited to matrices. 
It just so happens that in this example the replacement is a single 
dimension the same size as the single margin used.  That's atypical, and 
normally the result dimension has no connection to the margin.  The design 
is to put the result dimension first, and the first item in the 'seealso' 
list is aperm().

To my mind the only general solutions are to put the result dimension 
first or last.  I would have used last, but using first is slightly more 
efficient for the reason Pat gives.

apply() is for arrays, operating over one or more margins with a function 
returning a 'scalar', vector or array result.  Perhaps any 'lazy'-ness / 
limit of vision is not in handling array results as well as might be 
possible.

> Patrick Burns
> patrick at burns-stat.com
> +44 (0)20 8525 0696
> http://www.burns-stat.com
> (home of S Poetry and "A Guide for the Unwilling S User")


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list