[R] Re : Adding column sum to new row in data frame

David Winsemius dwinsemius at comcast.net
Thu May 20 14:43:29 CEST 2010

On May 20, 2010, at 1:01 AM, Joshua Wiley wrote:

> Dear Mohan,
> First, I would like to modify my code slightly to:
> data <- rbind(data,data.frame(State="Total",t(apply(data[,-1], 2, sum,
> na.rm=TRUE))))
> This actually will add a 7th level to your factor automatically.  The
> reason I wanted to change from using c() to data.frame() is that if
> one uses c(), all the columns are converted to character (this has to
> do with different methods for rbind, see ?rbind particularly the
> Details and Value section which describe the different methods for
> rbind and what its behavior will be if it is using the default
> method).  This may not be an issue, but it would hamper any subsequent
> calculations you may wish to perform on your data.

Actually the coercion to a single element type occurs as soon as you  
use c()

 > c("a", 1:10)
  [1] "a"  "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

Whether rbind might also coerce would depend on the class of arguments  
it is supplied. If you have created an argument with c() that is all  
character because that is the "least common denominator", and then try  
to rbind it to a dataframe, the numeric columns will character-ized.

David Winsemius, MD
West Hartford, CT

More information about the R-help mailing list