[R] colSum() in Matrix objects

Martin Maechler maechler at stat.math.ethz.ch
Tue Apr 17 09:43:48 CEST 2007


Hi Jose,

    Jose> I'd like to simply add column-wise using Matrix objects (Csparse).
    Jose> It looks like one can apply mosty any base function to these objects  
    Jose> (i.e., apply, colSums), but there is a nasty conversion to traditional  
    Jose> matrix objects if one does that.

not in this case, see below.

    Jose> Is there any workaround? I can see colSum listed in the help for Class  
colSums (final 's'!)

    Jose> 'CsparseMatrix' , but I wonder whether I'm using the default colSums() or  
    Jose> the one specific to CsparseMatrix...

      #example
      (z = Matrix(c(0,1,0,0), 10,10))
      zr = rowSums(z)
      class(zr) # numeric; I'd like it to be a CSparseMatrix object

  selectMethod("colSums", class(z))
## or
  showMethods("colSums")

both show you that you are using the class specific one.

However, why do you assume that colSums() should not return a
numeric vector?  From the idea that colSums() and rowSums()
should be fast versions of apply(., marg, sum),
it must return a numeric vector, as it also does for
traditional matrices.

Are your objects so huge that even a 1-row {or 1-column} sparse
matrix would save a lot?

Regards,
Martin Maechler, ETH Zurich



More information about the R-help mailing list