[R] apply() and dropped dimensions

From: Robin Hankin <r.hankin_at_noc.soton.ac.uk>
Date: Mon 05 Dec 2005 - 20:17:57 EST


Hi

I am having difficulty with apply(). I want apply() to return a matrix, but sometimes a vector is returned.

   Toy example follows.

Function jj() takes a couple of matrices m1 and m2 as arguments and returns a matrix with r rows and c columns where r=nrow(m2) and c=nrow(m1).

jj <- function(m1,m2,f,...){
   apply(m1, 1, function(y) {
   apply(m2, 1, function(x) {
      f(x, y, ...)

    })
  })
}

R> 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

intended behaviour: matrix returned. [eg, 70 = sum(m1[1,],m2[1,]) ]

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

R>

not intended behaviour: vector returned.

How do I rewrite jj() so that it consistently returns a matrix?

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743

______________________________________________
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 20:35:23 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:41:28 EST