[Rd] Dimension of apply(X, MARGIN, FUN) when FUN returns a matrix

Gabor Grothendieck ggrothendieck at myway.com
Tue Aug 31 18:55:47 CEST 2004


 <bhs2 <at> mevik.net> writes:

: 
: Dear all,
: 
: apply(X, MARGIN, FUN, ...) returns an array of dimension
: c(n, dim(X)[MARGIN]) when FUN returns a vector of length n > 1.
: 
: Matrices and arrays are also vectors, so if FUN returns a matrix or an
: array, apply returns an array of dimension c(n, dim(X)[MARGIN]) as
: above.  This is in accordance with the description of apply in the
: Blue Book, and also how Splus works (at least v6.0).
: 
: I am curious: why was it decided not to return an array of dimension
: c(dim(result.of.FUN), dim(X)[MARGIN]) when FUN returns a matrix or an
: array?
: 
: (This is not meant as criticism.  I am sure there is a good reason; I
: just cannot see it.)
: 


This does not answer your question but note that you can return the 
result as a list.  In the following apply is used to turn each column
of x into a 2x3 matrix returning the list of four such matrices:

R> x <- matrix(1:24,6)
R> apply(x, 2, function(x)list(matrix(x,2)))
[[1]]
[[1]][[1]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6


[[2]]
[[2]][[1]]
     [,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12


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


[[4]]
[[4]][[1]]
     [,1] [,2] [,3]
[1,]   19   21   23
[2,]   20   22   24



More information about the R-devel mailing list