[R] do.call("+", ...)

Duncan Murdoch murdoch at stats.uwo.ca
Fri Nov 17 14:46:22 CET 2006


On 11/17/2006 6:57 AM, Robin Hankin wrote:
> Hello everyone
> 
> thanks for the replies.  My application (predictably) involves
> arbitrary dimensioned arrays, so I will need to generalize
> the suggestions slightly (except Peter Dalgaard's, which
> works out-of-the-box).
> 
> At least I wasn't missing anything obvious about do.call().
> 
> Why is Peter Dalgaard's suggestion necessary?  Why can't  "+"
> take more than two arguments?

One reason is that it's a binary operator, so that's all it needs to 
take.  We have the sum function for multiple operands.

I would guess the historical reason is so that it can share code with 
other binary operators.  For example, + currently shares code with the 
other binary operators -, *, /, ^, %%, %/%, but the grouping needed 
varies between them:  a-b-c == (a-b)-c, but a^b^c == a^(b^c).  R lets 
the parser handle operator binding.

By the way, another complaint is that sum() is supposed to be generic, 
but you can't define a sum.matrix() method so that sum(a,b,c) does the 
same as a+b+c when a is a matrix.  (This would probably be a bad idea 
because people may be relying on the current behaviour, but R tries not 
to prevent people from testing out bad ideas.)  You need to apply your 
own class to the matrices (e.g. mymatrix), then it all works:

 > f  <- function(i){m <- matrix((1:6)^i,2,3); class(m) <- "mymatrix"; m}
 >
 > sum.mymatrix <- function(...) {
+     x <- list(...)
+     return(x[[1]] + do.call(sum, x[-1]))
+ }
 >
 > do.call("sum",sapply(1:4,f,simplify=FALSE))
      [,1] [,2] [,3]
[1,]    4  120  780
[2,]   30  340 1554
attr(,"class")
[1] "mymatrix"

Duncan Murdoch



More information about the R-help mailing list