Search code examples
rstatisticsdata-analysis

R row summing to a new column


I'm new to R and this is probablly a very simple question. I just haven't been able to make rsum/apply work

My task is to add all the different expense categories in my dataframe and create a new variable with this value like this:

(not the original)

Food      Dress    Car
235       564      532
452       632      719 
...       ...      ...

and then

Food      Dress    Car     Total
235       564      532     1331
452       632      719     1803
...       ...      ...     ...

I have tried:

rowsum, apply and aggregate and can't get it right


Solution

  • You can use addmargins after converting to matrix

     addmargins(as.matrix(df1),2)
    #     Food Dress Car  Sum
    #[1,]  235   564 532 1331
    #[2,]  452   632 719 1803
    

    Or use rowSums

    df1$Total <- rowSums(df1)
    

    Or with Reduce

    df1$Total <-  Reduce(`+`, df1)