I would like to append a columns to my data.frame in R that contain row sums and products Consider following data frame
x y z
1 2 3
2 3 4
5 1 2
I want to get the following
x y z sum prod
1 2 3 6 6
2 3 4 9 24
5 1 2 8 10
I have tried
sum = apply(ages,1,add)
but it gives me a row vector. Can some one please show me an efficient command to sum and product and append them to original data frame as shown above?
Another approach.
Try
Or
Another option would be to use
rowProds
frommatrixStats
If you are using
apply
Following can also be done but column names need to be entered:
With data.table, another form can be:
A simpler version is suggested by @David Arenberg in comments:
Only a partial answer, but if all values are greater than or equal to 0, rowSums/rowsum can be used to calculate products:
The generic version is (including negatives):