I am learning R and have written some code which produces the desired outputs but uses loops, which I would like to reply with some type of apply function.
I have a data frame, results, which stores outcomes of matches of a two-player game.
Player1 Player2 Result
Alice Bob Win
Charlie Dennis Win
Elena Frank Loss
...
And another, scores, which stores each player's overall score.
Player Score
Alice 1200
Charlie 1200
Frank 1200
Bob 800
Dennis 800
Elena 800
...
The way the scores are calculated is using a function which takes in a single result, the current scores, and returns a new data frame with the new scores.
updateScores <- function(result, scores) {
[ Code that calculates new scores based on a single result ]
return(scores)
}
Now the problem is that I want to loop through the results and update the scores table. This is trivial with a for loop:
for(i in 1:nrow(results)) {
scores <- updateScores(results[i, ], scores)
}
But I am struggling to see how I can do this with apply, mapply, or any other functional way which avoids the loop. This is because the scores variable needs to be passed to updateScores and updated with every iteration. (In Lisp I would use the reduce function but in R, Reduce() doesn't work the same way.)