New to R. Little reputation of my df:
PTS_TeamHome <- c(101,87,94,110,95)
PTS_TeamAway <- c(95,89,105,111,121)
TeamHome <- c("LAL", "HOU", "SAS", "MIA", "LAL")
TeamAway <- c("IND", "LAL", "LAL", "HOU", "NOP")
df <- data.frame(cbind(TeamHome, TeamAway,PTS_TeamHome,PTS_TeamAway))
df
TeamHome TeamAway PTS_TeamHome PTS_TeamAway
LAL IND 101 95
HOU LAL 87 89
SAS LAL 94 105
MIA HOU 110 111
LAL NOP 95 121
Imagine that this is the first four games of the season with 1230 games. I want to calculate the total points per game (on average) at any given time for the home team and the guest team.
The result will look like this:
TeamHome TeamAway PTS_TeamHome PTS_TeamAway HOMETEAM_AVGCUMPTS ROADTEAM_AVGCUMPTS
1 LAL IND 101 95 101 95
2 HOU LAL 87 89 87 95
3 SAS LAL 94 105 94 98.33
4 MIA HOU 110 111 110 99
5 LAL NOP 95 121 97.5 121
Please note that the formula for the fifth game is for the home team. Since LAL is a home team, it looks for how many points the LAL has when played at home or on the go. In this case (101 + 89 + 105 + 95) / 4 = 97.5
Here is what I tried without much success:
lst <- list()
for(i in 1:nrow(df)) lst[[i]] <- ( cumsum(df[which(df$TEAM1[1:i]==df$TEAM1[i]),df$PTS_TeamAway,0])
+ cumsum(df[which(df$TEAM2[1:i]==df$TEAM1[i]),df$PTS_TeamHome,0]) )
/
df$HOMETEAM_AVGCUMPTS <- unlist(lst)
I wanted to calculate the cumulative PTS and then the number of games to separate it, but none of this worked.