0

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

Alfredo Lozano
  • 290
  • 1
  • 3
  • 15

2 Answers2

7

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

With apply functions:

cbind(dat, Total = apply(dat, 1, sum))
  Food Dress Car Total
1  235   564 532  1331
2  452   632 719  1803

or with just a:

 cbind(dat, Total = rowSums(dat))
  Food Dress Car Total
1  235   564 532  1331
2  452   632 719  1803
SabDeM
  • 7,050
  • 2
  • 25
  • 38