[Rd] RFC: sapply() limitation from vector to matrix, but not further
Tony Plate
tplate at acm.org
Tue Dec 28 19:14:36 CET 2010
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:
>>>>>> Gabor Grothendieck<ggrothendieck at gmail.com>
>>>>>> on Mon, 27 Dec 2010 17:06:25 -0500 writes:
> > On Wed, Dec 1, 2010 at 3:39 AM, Martin Maechler
> > <maechler at stat.math.ethz.ch> wrote:
> >> My proposal -- implemented and "make check" tested -- is
> >> to add an optional argument 'ARRAY' which allows
> >>
> >>> sapply(v, myF, y = 2*(1:5), ARRAY=TRUE)
>
> > It would reduce the proliferation of arguments if the
> > simplify= argument were extended to allow this,
> > e.g. simplify = "array" or perhaps simplify = n would
> > allow a maximum of n dimensions.
>
> That's a good idea, though it makes the
> implementation/documentation very slightly more complicated.
>
> I'm interested to get more feedback on my other questions,
> notably the only about *changing* vapply() (on the C-level) to
> behave "logical" in the sense of adding one dim(.)ension in
> those cases, the FUN.VALUE (result prototype) has a dim().
>
>
> Martin
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list