I have tried using rollapply but I can't get the desired result.
These are the columns(sample) of the dataset on which I want to do the calculations.
structure(list(LeagueROUND = structure(c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("1", "2",
"3", "4"), class = "factor"), League = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Portugal2", class = "factor"),
Season = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "2021/2022", class = "factor"),
DRAWmarginODDS = structure(c(2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"),
DRAWnumODDS = c(0L, NA, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L,
0L, 0L, NA, 0L)), .Names = c("LeagueROUND", "League", "Season",
"DRAWmarginODDS", "DRAWnumODDS"), class = "data.frame", row.names = c(NA,
-15L))
Desired result
Group by( LeagueROUND,League,Season,DRAWmarginODDS)
Average(mean) of (DRAWnumODDS) of 3 previous LeagueROUNDs
That is:
League Round 1 (Yes) adds 1(DRAWnumODDS) in 3(grouped) rows.
League Round 2 (Yes) adds 2(DRAWnumODDS) in 4(grouped) rows
League Round 3 (Yes) adds 0(DRAWnumODDS) in 3(grouped) rows
Desired:
In League Round 4(Yes) (average of 3 previous League Round) = 3(DRAWnumODDS) in 10(grouped) rows = mean 0,3
League Round (No) = NA
3 first LeagueROUND -> NA