Re: [R] apply() and dropped dimensions

From: Berwin A Turlach <berwin_at_maths.uwa.edu.au>
Date: Mon 05 Dec 2005 - 21:03:26 EST

G'day Robin,

>>>>> "RH" == Robin Hankin <r.hankin@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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Mon Dec 05 21:10:39 2005

This archive was generated by hypermail 2.1.8 : Mon 05 Dec 2005 - 23:31:10 EST