Edit: I wrote the question way to unstructured, let me try again.
I want to create two new columns, winner_total_points
and loser_total_points
to the dataset below.
winner <- c(1,2,3,4,1,2)
loser <- c(2,3,1,3,3,1)
winner_points <- c(5,4,12,2,1,6)
loser_points <- c(5,2,2,6,6,2)
test_data <- data.frame(winner, loser, winner_points, loser_points)
What I want those two columns to do is that winner_total_points
to sum all the points the winner has gotten (excluding this match) as both the winner and the loser.
The same function for loser_total_points
but for the loser.
Note that the winner
and loser
columns contain the respective player ids.
Now, it's fairly easy using the ave()
function but that only works for grouping only column and doing the cumulative sum for one column.
Desired output:
winner loser winner_points loser_points winner_total loser_total
1 2 5 5 5 5
2 3 4 2 9 (5+4) 2
3 1 12 2 14 (2+12) 7 (5+2)
4 3 2 6 2 20 (2+12+6)
1 3 1 6 8 (5+2+1) 26 (2+12+6+6)
2 1 6 2 15 (5+4+6) 10 (5+2+1+2)