[Rd] apply with zero-row matrix

William Dunlap wdunl@p @ending from tibco@com
Mon Aug 13 23:41:36 CEST 2018


vapply has a mandatory FUN.VALUE argument which specifies the type and size
of FUN's return value.  This helps when you want to cover the 0-length case
without 'if' statements.  You can change your apply calls to vapply calls,
but they will be a bit more complicated.  E.g.,  change
   apply(X=myMatrix, MARGIN=2, FUN=quantile)
to
   vapply(seq_len(ncol(myMatrix)), FUN=function(i)quantile(myMatrix[,i]),
FUN.VALUE=numeric(5))

The latter will always return a 5-row by ncol(myMatrix) matrix.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Jul 30, 2018 at 5:38 AM, Martin Maechler <maechler using stat.math.ethz.ch
> wrote:

> >>>>> David Hugh-Jones
> >>>>>     on Mon, 30 Jul 2018 10:12:24 +0100 writes:
>
>     > Hi Martin, Fair enough for R functions in general. But the
>     > behaviour of apply violates the expectation that apply(m,
>     > 1, fun) calls fun n times when m has n rows.  That seems
>     > pretty basic.
>
> Well, that expectation is obviously wrong ;-)  see below
>
>     > Also, I understand from your argument why it makes sense
>     > to call apply and return a special result (presumably
>     > NULL) for an empty argument; but why should apply call fun?
>
>     > Cheers David
>
> The reason is seen e.g. in
>
>     > apply(matrix(,0,3), 2, quantile)
>          [,1] [,2] [,3]
>     0%     NA   NA   NA
>     25%    NA   NA   NA
>     50%    NA   NA   NA
>     75%    NA   NA   NA
>     100%   NA   NA   NA
>     >
>
> and that is documented (+/-) in the first paragraph of the
> 'Value:' section of help(apply) :
>
>  > Value:
>  >
>  >      If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’
>  >      returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’.
>  >      If ‘n’ equals ‘1’, ‘apply’ returns a vector if ‘MARGIN’ has length
>  >      1 and an array of dimension ‘dim(X)[MARGIN]’ otherwise.  If ‘n’ is
>  >      ‘0’, the result has length 0 but not necessarily the ‘correct’
>  >      dimension.
>
>
> To determine 'n', the function *is* called once even when
> length(X) ==  0
>
> It may indeed be would helpful to add this explicitly to the
> help page  ( <R>/src/library/base/man/apply.Rd ).
> Can you propose a wording (in *.Rd if possible) ?
>
> With regards,
> Martin
>
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

	[[alternative HTML version deleted]]



More information about the R-devel mailing list