From m@echler @ending from @t@t@m@th@ethz@ch  Mon Jul 30 09:41:39 2018
From: m@echler @ending from @t@t@m@th@ethz@ch (Martin Maechler)
Date: Mon, 30 Jul 2018 09:41:39 +0200
Subject: [Rd] apply with zero-row matrix
In-Reply-To: <CAARY7kjL=buR9GE9rP8Y64D_WTdrFunfTMUXD2mw8P4gMsNrTQ@mail.gmail.com>
References: <CAARY7khVXzxutThhKcq+ZftTE8-66eH-B-82xs-8TFyTTmGrkw@mail.gmail.com>
 <CAARY7kjL=buR9GE9rP8Y64D_WTdrFunfTMUXD2mw8P4gMsNrTQ@mail.gmail.com>
Message-ID: <23390.49459.112386.395212@stat.math.ethz.ch>

>>>>> David Hugh-Jones 
>>>>>     on Mon, 30 Jul 2018 05:33:19 +0100 writes:

    > Forgive me if this has been asked many times before, but I
    > couldn't find anything on the mailing lists.

    > I'd expect apply(m, 1, foo) not to call `foo` if m is a
    > matrix with zero rows.  In fact:

    > m <- matrix(NA, 0, 5)
    > apply(m, 1, function (x) {cat("Called...\n"); print(x)})
    > ## Called...
    > ## [1] FALSE FALSE FALSE FALSE FALSE


    > Similarly for apply(m, 2,...) if m has no columns.  Is
    > there a reason for this?

Yes :

The reverse is really true for almost all basic R functions:

    They *are* called and give an "empty" result automatically
    when the main argument is empty.

What you basicaly propose is to add an extra

     if(<length 0 input>)
     	 return(<correspondingly formatted length-0 output>)

to all R functions.  While that makes sense for high-level R
functions that do a lot of things, this would really be a bad
idea in general :

This would make all of these basic functions larger {more to maintain} and
slightly slower for all non-zero cases just to make them
slightly faster for the rare zero-length case.

Martin Maechler
ETH Zurich and R core Team



[Rd] apply with zero-row matrix
Martin Maechler