[R] apply() and dropped dimensions

Robin Hankin r.hankin at noc.soton.ac.uk
Mon Dec 5 10:17:57 CET 2005


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




More information about the R-help mailing list