[R] Column sums from a data frame (without the headers)

Gavin Simpson gavin.simpson at ucl.ac.uk
Fri Feb 29 18:15:02 CET 2008


On Fri, 2008-02-29 at 12:02 -0500, Jason Horn wrote:
> Does anyone know how to get a vector of column sum from a data frame?   
> You can use colSums(), but this gives you a object of type "numeric"  
> with the column labels in the first row, and the sums in the second  
> row.  I just want a vector of the sums, and I can't figure out a way  
> to index the "numeric" object.
> 
> Thanks!

The labels you are seeing are just the 'names' attribute of the vector
of column sums that is being printed. You can ignore them for most uses
such as using them in some computations:

> df <- data.frame(A = runif(10), B = runif(10), C = rnorm(10))
> colSums(df)
        A         B         C 
 5.982975  5.566133 -4.696136 
> str(colSums(df))
 Named num [1:3]  5.98  5.57 -4.70
 - attr(*, "names")= chr [1:3] "A" "B" "C"
> colSums(df) * 4
        A         B         C 
 23.93190  22.26453 -18.78454

If you really need to get rid of the names:

> unname(colSums(df))
[1]  5.982975  5.566133 -4.696136

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list