I am trying to create a new variable in my dataframe that is the group-specific sum of a variable. For example:
df <- data.frame (group = c(1, 1, 1, 2, 2, 2),
variable = c(1, 2, 1, 3, 4, 5)
)
df
group variable
1 1 1
2 1 2
3 1 1
4 2 3
5 2 4
6 2 5
I would like a new variable that sums variable by group to get something that looks like this:
group variable sum
1 1 1 4
2 1 2 4
3 1 1 4
4 2 3 12
5 2 4 12
6 2 5 12
Thank you!