[R] do.call("+", ...)
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Fri Nov 17 15:14:58 CET 2006
Duncan Murdoch <murdoch at stats.uwo.ca> writes:
> 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.
Ah, yes. This also means that my suggestion doesn't work unless "+" is
associative, since
> quote(a+b+c)[[3]]
c
> quote(a+b+c)[[2]]
a + b
so a+b+c is really (a+b)+c and I was calculating a+(b+c). That's
actually a little bit harder because you don't get help from argument
matching:
"++" <- function(...) if ((n <- nargs()) == 1) ..1 else {
l <- list(...)
do.call("++",l[-n]) + l[[n]]
}
> do.call("++", sapply(1:4, f, simplify=FALSE))
[,1] [,2] [,3]
[1,] 4 120 780
[2,] 30 340 1554
and just to rub it in, notice that things like recycling can destroy
associativity:
> 1:2 + (1:3 + 1:5)
[1] 3 6 7 7 8
Warning messages:
1: longer object length
is not a multiple of shorter object length in: 1:3 + 1:5
2: longer object length
is not a multiple of shorter object length in: 1:2 + (1:3 + 1:5)
> (1:2 + 1:3) + 1:5
[1] 3 6 7 6 9
Warning messages:
1: longer object length
is not a multiple of shorter object length in: 1:2 + 1:3
2: longer object length
is not a multiple of shorter object length in: (1:2 + 1:3) + 1:5
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list