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

Erik Iverson iverson at biostat.wisc.edu
Fri Feb 29 18:14:40 CET 2008


Jason -

colSums does return an object of class "numeric", which is certainly a 
vector.  The vector it returns happens to have names.  If you want an 
unnamed vector of the sums, just set the names attribute to NULL. This 
will remove the names.  However, you say you can't figure out how to 
index the object that colSums returns.  You index it just like any other 
vector, but you can use names in addition.

## ALL UNTESTED!
## test data.frame
testdf <- data.frame(a = rnorm(10), b = rnorm(10))
cs <- colSums(testdf)

class(cs)  ## numeric
is.vector(cs)  ## TRUE
names(cs) ## look at the names of the vector

cs[1] ## first element of cs
cs["a"] ## same as above

## get rid of names attribute
names(cs) <- NULL
cs  ## look at cs, no more names
cs[1] ## still works
cs["a"] ## no longer works

Best,
Erik Iverson

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



More information about the R-help mailing list