Reputation: 47
This is probably an easy question to answer, but I haven't been able to find a solution.
Assume I have the following dataframe:
Name Value
Bob 100
Bob 500
Jim 50
Rach 300
Rach 300
Rach 300
I need to create a new column that adds the value for each person. The end result should look something like this:
Name Value Sum
Bob 100 600
Bob 500 600
Jim 50 50
Rach 300 900
Rach 300 900
Rach 300 900
Thank you in advance for any help with this problem.
Upvotes: 0
Views: 1742
Reputation: 557
Another simple solution is:
dat <- data.frame(Name = c('Bob', 'Bob', 'Jim', 'Rach', 'Rach', 'Rach'),
Value = c(100, 500, 50, 300, 300, 300))
transform(dat, sum_name = ave(Value, Name, FUN = sum))
Upvotes: 3
Reputation: 60924
plyr
is your friend:
library(plyr)
ddply(dat, .(Name), transform, sum_name = sum(Value))
Name Value sum_name
1 Bob 100 600
2 Bob 500 600
3 Jim 50 50
4 Rach 300 900
5 Rach 300 900
6 Rach 300 900
Assuming your data is in the data.frame
dat
. For other possible solutions take a look at the data.table
package and the R base functions aggregate
, by
, split
.
Upvotes: 1