[Rd] small bug in apply() ??? (PR#7205)

From: <gunter.berton_at_gene.com>
Date: Tue 31 Aug 2004 - 03:21:16 EST


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



R-devel@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue Aug 31 03:24:33 2004

This archive was generated by hypermail 2.1.8 : Wed 03 Nov 2004 - 22:45:11 EST