[Rd] Controlling simplification in apply()?

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Feb 21 08:09:18 CET 2012

On 20/02/2012 16:03, Gavin Simpson wrote:
> Dear list,
> Fully according to the documented behaviour, I was bitten by apply()
> simplifying results to vectors or arrays when the lengths of the
> individual objects returns by FUN are the same (over simplification).
> sapply() has argument simplify with default TRUE to control whether it
> attempts to simplify the returned objects or not.
> I do find it a little annoying that one is not able to force apply into
> one behaviour or the other.

I think it is different.  sapply (and mapply) work on a list and return 
a list result unless simplified.  apply() works on an array and returns 
an array result (dropping dims to a vector) unless that is not possible.

We don't have an example, but you seem to want a list result from 
apply().  If that _is_ what you want, why not use lapply()?  E.g.

lapply(split(m, row(m)), max)

is the list equivalent of apply(m, 1, max) .  Also, apply() is just 
sugar around a for() loop, and a loop may do what you want.

> Would the be merit in apply() also having a similar argument to control
> whether simplification occurs or not, say adding `simplify = TRUE` after
> `...`? If there was I'd be happy to provide a first stab and contribute
> updated documentation.
> All the best,
> Gavin

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-devel mailing list