[R] sum

John Fox jfox at mcmaster.ca
Wed Apr 23 22:52:45 CEST 2003


Dear Luis,

On Wednesday 23 April 2003 12:57 pm, Luis Silva wrote:
 > I have a list where each element is a matrix (the list is
 > obtained with lapply). I want to sum those matrices. Is there a
 > function to do that? The sum function sums all the elements...

Here's a recursive function that works with a list of two or more matrices:

     sumMatrices <- function(matrices){
         if (length(matrices) > 2) matrices[[1]] + Recall(matrices[-1])
         else matrices[[1]] + matrices[[2]]
         }

Regards,
  John



-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox



More information about the R-help mailing list