[R] apply() and dropped dimensions

Berwin A Turlach berwin at maths.uwa.edu.au
Mon Dec 5 11:03:26 CET 2005


G'day Robin,

>>>>> "RH" == Robin Hankin <r.hankin at noc.soton.ac.uk> writes:

    RH> How do I rewrite jj() so that it consistently returns a
    RH> matrix?
How about explicitly returning a matrix with the desired dimensions?

> jj
function(m1,m2,f,...)
    matrix(apply(m1, 1, function(y) 
                 apply(m2, 1, function(x)
                       f(x, y, ...)
                       )),
           nrow=nrow(m2), ncol=nrow(m1))

> jj(matrix(1:20,4,5),matrix(1:10,2,5),f=sum)
     [,1] [,2] [,3] [,4]
[1,]   70   75   80   85
[2,]   75   80   85   90

> jj(matrix(1:20,4,5),matrix(1:5,1,5),f=sum)
     [,1] [,2] [,3] [,4]
[1,]   60   65   70   75


Or, using the outer command:

> jj
function(m1,m2,f,...)
    outer(1:nrow(m2), 1:nrow(m1), function(i,j) apply(cbind(i,j), 1, function(ii)  f(m2[ii[1],], m1[ii[2],], ...)))

> jj(matrix(1:20,4,5),matrix(1:10,2,5),f=sum)
     [,1] [,2] [,3] [,4]
[1,]   70   75   80   85
[2,]   75   80   85   90

> jj(matrix(1:20,4,5),matrix(1:5,1,5),f=sum)
     [,1] [,2] [,3] [,4]
[1,]   60   65   70   75

Cheers,

        Berwin




More information about the R-help mailing list