Skip to content
Prev 38755 / 63424 Next

RFC: sapply() limitation from vector to matrix, but not further

The abind() function from the abind package is an alternative here -- it can take a list argument, which makes it easy to use with the result of lapply().  It's also able take direction about which dimension to join on.

 > x <- list(a=1,b=2,c=3)
 > f <- function(v) matrix(v, nrow=2, ncol=4)
 > sapply(x, f)
      a b c
[1,] 1 2 3
[2,] 1 2 3
[3,] 1 2 3
[4,] 1 2 3
[5,] 1 2 3
[6,] 1 2 3
[7,] 1 2 3
[8,] 1 2 3
 >
 > # The 'along=' argument to abind() determines on which dimension
 > # the list elements are joined.  Use a fractional value to put the new
 > # dimension between existing ones.
 >
 > dim(abind(lapply(x, f), along=0))
[1] 3 2 4
 > dim(abind(lapply(x, f), along=1.5))
[1] 2 3 4
 > dim(abind(lapply(x, f), along=3))
[1] 2 4 3
 > abind(lapply(x, f), along=3)
, , a

      [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    1    1

, , b

      [,1] [,2] [,3] [,4]
[1,]    2    2    2    2
[2,]    2    2    2    2

, , c

      [,1] [,2] [,3] [,4]
[1,]    3    3    3    3
[2,]    3    3    3    3

 >
On 12/28/2010 8:49 AM, Martin Maechler wrote: