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

rfrancois at mango-solutions.com rfrancois at mango-solutions.com
Fri Nov 17 11:17:35 CET 2006


Hi,

You could stack your list in an array and then use apply :

myArray <- array( unlist(lapply(1:3, f) ) , dim =c(2, 3, 3))
apply(myArray, c(1,2), sum)

Cheers,

Romain

Quoting Robin Hankin <r.hankin at noc.soton.ac.uk>:

> Hi
>
> How do I make do.call() take "+" as a function for a list of more
> than two elements?
>
> Toy problem follows:
>
>
> f  <- function(i){matrix((1:6)^i,2,3)}
>
> # Thus f() returns a matrix of size 2x3; I want to add a whole bunch
> of such matrices,
> # as in  f(1) + f(2) + f(3) + f(4)
>
> # But:
>
>
>
>  > do.call("+",sapply(1:4,f,simplify=FALSE))
> Error in do.call("+", sapply(1:4, f, simplify = FALSE)) :
> 	operator needs one or two arguments
>
>
>
>
> Also,
>
>
>  > do.call(sum,sapply(1:4,f,simplify=FALSE))
> [1] 2828
>
>
> doesn't do what I want (I would like a 2x3 matrix whose elements are the
> sum of corresponding elements in my list)
>
> How to do this nicely?
>
>
>
>
>
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
>   tel  023-8059-7743
>
> ______________________________________________
> R-help at 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
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list