R 行求和到一个新列

R row summing to a new column

我是 R 的新手,这可能是一个非常简单的问题。 我只是无法让 rsum/apply 工作

我的任务是在我的数据框中添加所有不同的费用类别,并使用如下值创建一个新变量:

(非原文)

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

然后

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

我试过:

rowsum, apply and aggregate 搞不对

转换为matrix后即可使用addmargins

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

或使用rowSums

df1$Total <- rowSums(df1)

Reduce

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

具有apply个功能:

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

或者只用一个:

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