From gunter.berton at gene.com  Mon Aug 30 19:21:16 2004
From: gunter.berton at gene.com (gunter.berton@gene.com)
Date: Mon Aug 30 19:21:21 2004
Subject: [Rd] small bug in apply() ??? (PR#7205)
Message-ID: <20040830172116.1B599EAC0@slim.kubism.ku.dk>

System: R 1.9.1 on Windows 2000.

Description of problem:

So far as I can tell, this occurs only when using apply() on an array of
dimension >=3 AND when for each iteration the function returns a named
vector of length >=2. I propose the source of the bug and the fix below,
but let me stick to the facts first.

Here is an example:

>a<-array(1:24, dim=2:4)
> func1<-function(x)c(a=mean(x),b=max(x))
> func2<-function(x)c(mean(x),max(x))
> apply(a,1:2,func1)
Error in array(ans, c(len.a%/%d2, d.ans), if (is.null(dn.ans)) { :
        length of dimnames [2] must match that of dims [3]
> apply(a,1:2,func2)
, , 1

     [,1] [,2]
[1,]   10   11
[2,]   19   20

, , 2

     [,1] [,2]
[1,]   12   13
[2,]   21   22

, , 3

     [,1] [,2]
[1,]   14   15
[2,]   23   24

******************
The problem appears to be in the next to last line of apply in the
"list" construction

if (len.a > 0 && len.a%%d2 == 0)
        return(array(ans, c(len.a%/%d2, d.ans), if (is.null(dn.ans)) {
            if (!is.null(ans.names)) *****list(ans.names, NULL) ****
        } else c(list(ans.names), dn.ans)))
    return(ans)
}

As the error message says, the dimnames list is the wrong length. I
believe the following change fixes the problem, though someone much more
familiar with the code will need to check and/or improve it:

 if (len.a > 0 && len.a%%d2 == 0)
        return(array(ans, c(len.a%/%d2, d.ans), if (is.null(dn.ans)) {
            if (!is.null(ans.names))
*****c(list(ans.names),vector(mode="list",length(d.ans)))  *****
        } else c(list(ans.names), dn.ans)))
    return(ans)
}

With this change, both my examples (and others) ran fine.

I checked the bug list and didn't find this problem, but if I just
missed it, I apologize for wasting your time. While I am here, let me
again take the opportunity to say that I continue to be amazed by the R
phenomenon. I appreciate the hard work that you all do, and I am
astounded by the patience you display on R-help answering questions from
people who for reasons I cannot fathom, won't read the excellent
documentation that you all have written. Sometimes I get exasperated
just reading the questions, let alone answering them.

Cheers,

Bert Gunter
Genentech


[Rd] small bug in apply() ??? (PR#7205)
gunter.berton@gene.com