I have a data frame of sports games and want to get the average of the previous n points. For example, my data frame looks like this:
Home Away Home Away
Team Team Points Points
1 Red Green 2 1
2 Green Blue 3 4
3 Blue Red 4 3
4 Red Blue 2 4
5 Blue Green 4 2
6 Green Red 3 3
I'd like to have a new column for home team and away team average points in their last 2 games. I think that by creating a new column with both team names in it, I should be able to use str_detect to get the average points over the last n occurrences.
For example, In the above example, I'd like to take an average of the points scored for both teams over their last 2 games. What I'd like the outcome to look like is this:
Home Away Home Away Game Avg Points Avg Points
Team Team Points Points ID (Home Team) (Away Team)
1 Red Green 2 1 2020_1_Red_Green NA NA
2 Green Blue 3 4 2020_2_Green_Blue NA NA
3 Blue Red 4 3 2020_3_Blue_Red NA NA
4 Red Blue 2 4 2020_4_Red_Blue 2.5 4
5 Blue Green 4 2 2020_5_Blue_Green 4 2
6 Green Red 3 3 2020_Green_Red 2.5 2.5
I think the answer will require some type of str_detect, but I'm not sure how to find the last n number of games that either team has played.
What is a way to accomplish this?