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

Joshua Wiley jwiley.psych at gmail.com
Wed May 19 20:23:27 CEST 2010


Dear Mohan,

Is this what you want?

rbind(data, c("Total",apply(data[,-1], 2, sum, na.rm=TRUE)))

If your State column is a factor, it will return a warning that NAs
were introduced (but the totals will still be at the bottom).  If
State is class character, then that row will have a name "Total" and
then the numbers.

Best regards,

Josh

On Wed, May 19, 2010 at 10:52 AM, Mohan L <l.mohanphy at gmail.com> wrote:
> Dear All,
>
> I have data some thing like this:
>
>    State Jan Feb Mar Apr May Jun  AAA 1 1 0 2 2 0  BBB 1298 1195 1212 1244
> 1158 845  CCC 0 0 0 1 2 1  DDD 5 11 17 15 10 9  EEE 18 28 27 23 23 16  FFF
> 68 152 184 135 111 86
>
>
> I want to sum all the column(Jan, Feb, Mar ...) and have to merge the total
> at last row. like this:
>
> StateJanFebMarAprMayJunAAA110220BBB12981195121212441158845CCC 000121DDD51117
> 15109EEE182827232316FFF6815218413511186Total    1390 1387 1440 1420 1306
> 957
>
>
> I am doing some thing like this, but I don't know how to merge "Total" to
> "data"  Or I don't know there may be a alternative way.
>
>> data <- read.csv(file='ipsample.csv',sep=',' , header=TRUE)
>> data
>  State  Jan  Feb  Mar  Apr  May Jun
> 1   AAA    1    1    0    2    2   0
> 2   BBB 1298 1195 1212 1244 1158 845
> 3  CCC     0    0    0    1    2   1
> 4   DDD    5   11   17   15   10   9
> 5   EEE   18   28   27   23   23  16
> 6   FFF   68  152  184  135  111  86
>
>> attributes(data)
> $names
> [1] "State" "Jan"   "Feb"   "Mar"   "Apr"   "May"   "Jun"
>
> $class
> [1] "data.frame"
>
> $row.names
> [1] 1 2 3 4 5 6
>
>
>> x <- data[,2:ncol(data)]
>
>> x
>
>   Jan  Feb  Mar  Apr  May Jun
> 1    1    1    0    2    2   0
> 2 1298 1195 1212 1244 1158 845
> 3    0    0    0    1    2   1
> 4    5   11   17   15   10   9
> 5   18   28   27   23   23  16
> 6   68  152  184  135  111  86
>
>> Total <- sapply(x,sum,na.rm=T)
>
>> Total
>  Jan  Feb  Mar  Apr  May  Jun
> 1390 1387 1440 1420 1306  957
>
> I hope there may be alternative way.  Any help will be appreciated.
>
> Thanks & Rg
> Mohan L
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Senior in Psychology
University of California, Riverside
http://www.joshuawiley.com/



More information about the R-help mailing list