I have this dataframe here:
smallerDF <- structure(list(category = c("Opponent", "Opponent", "Opponent",
"Opponent", "P1", "P2", "P3", "P2", "P2", "Opponent", "Opponent",
"P1"), Event = c("Good Pass", "Good Pass", "Good Pass", "Turnover",
"Good Pass", "Good Pass", "Good Pass", "Good Pass", "Bad Pass",
"Intercepted Pass", "Bad Pass", "Good Pass"), Value = c(2, 2,
2, -3, 2, 2, 2, 2, -2, 1, -2, 2), `Score Sum` = c(2, 4, 6, 3,
2, 4, 6, 8, 6, 1, -1, 2)), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
It contains 4 columns and 12 rows. In the 3rd column are values that were assigned based on the event. In the 4th column, I am trying to add the values to get a rolling sum. So for every time the Opponent had an event, their current value would be added to their previous score sum, and similar for P1/P2/P3. I have been able to roll the sums to how I expect it to be up until row 10.
I have the following code written here:
for (i in 1:nrow(smallerDF)) {
#print(i)
if (smallerDF$Event[i] == "Good Pass") {
smallerDF$Value[i] <- 2
}
if (smallerDF$Event[i] == "Bad Pass") {
smallerDF$Value[i] <- -2
}
if (smallerDF$Event[i] == "Intercepted Pass") {
smallerDF$Value[i] <- 1
}
if (smallerDF$Event[i] == "Turnover") {
smallerDF$Value[i] <- -3
}
if (smallerDF$category[i] == "Opponent") {
#print(i)
if (i != 1 && smallerDF$category[i-1] == "Opponent") {
smallerDF$`Score Sum`[i] <- smallerDF$Value[i] + smallerDF$`Score Sum`[i-1]
}
}
else if (smallerDF$category[i] %in% dfList) {
if (i != 1 && smallerDF$category[i-1] %in% dfList) {
smallerDF$`Score Sum`[i] <- smallerDF$Value[i] + smallerDF$`Score Sum`[i-1]
}
}
}
This works up until row 10 since I am using [i-1], but I can't figure out how to get row 10 to reference back to row 4 (the last time Opponent was used) to add cell [10,3] onto cell [4,4].
The final result should look like
category Event Value `Score Sum`
<chr> <chr> <dbl> <dbl>
1 Opponent Good Pass 2 2
2 Opponent Good Pass 2 4
3 Opponent Good Pass 2 6
4 Opponent Turnover -3 3
5 P1 Good Pass 2 2
6 P2 Good Pass 2 4
7 P3 Good Pass 2 6
8 P2 Good Pass 2 8
9 P2 Bad Pass -2 6
10 Opponent Intercepted Pass 1 4
11 Opponent Bad Pass -2 2
12 P1 Good Pass 2 8
I tried incorporating the use of this code
dt <- data.table(smallerDF)
newDT <- dt[ , .SD[.N] , by = c("category") ]
but this only returns the very last row for each different value in category, and not the latest/previous occurrence of the category.
Any help would be greatly appreciated. Thanks