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

From: Gavin Simpson <gavin.simpson_at_ucl.ac.uk>
Date: Fri, 29 Feb 2008 17:15:02 +0000

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

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
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

______________________________________________
R-help_at_r-project.org 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.
Received on Fri 29 Feb 2008 - 17:20:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 29 Feb 2008 - 18:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive