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

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.be
Fri Nov 17 10:38:01 CET 2006


try the following:

mat.lis <- lapply(1:4, f)
matFun(mat.lis, sum)

where

matFun <- function(lis, FUN){
    if(!is.list(lis) || !all(sapply(lis, is.matrix)))
        stop("'lis' must be a list containing 2-dimensional arrays")
    dims <- sapply(lis, dim)
    n <- dims[1, 1]
    p <- dims[2, 1]
    if(!all(n == dims[1, ]) || !all(p == dims[2, ]))
        stop("the matrices must have the same dimensions")
    mat <- matrix(unlist(lis), n * p, length(lis))
    matrix(apply(mat, 1, FUN), n, p)
}


you can make it a bit more efficient if you replace "apply(mat, 1, 
FUN)" with rowSums() and rowMeans whenever FUN is "sum" or "mean", 
respectively.

I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm



----- Original Message ----- 
From: "Robin Hankin" <r.hankin at noc.soton.ac.uk>
To: "RHelp help" <r-help at stat.math.ethz.ch>
Sent: Friday, November 17, 2006 10:24 AM
Subject: [R] do.call("+", ...)


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


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



More information about the R-help mailing list