Skip to content

Commit a32b758

Browse files
committed
pseudocode for accepting a filtered pbp
1 parent 2180816 commit a32b758

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

R/calculate_stats.R

+12-5
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,17 @@
3131
calculate_stats <- function(seasons = nflreadr::most_recent_season(),
3232
summary_level = c("season", "week"),
3333
stat_type = c("player", "team"),
34-
season_type = c("REG", "POST", "REG+POST")){
34+
season_type = c("REG", "POST", "REG+POST"),
35+
pbp = NULL){
3536

3637
summary_level <- rlang::arg_match(summary_level)
3738
stat_type <- rlang::arg_match(stat_type)
3839
season_type <- rlang::arg_match(season_type)
40+
custom_pbp <- !is.null(pbp)
41+
42+
if (custom_pbp) validate_pbp(pbp)
43+
if (!custom_pbp) pbp <- nflreadr::load_pbp(seasons = seasons)
3944

40-
pbp <- nflreadr::load_pbp(seasons = seasons)
4145
if (season_type %in% c("REG", "POST") && summary_level == "season") {
4246
pbp <- dplyr::filter(pbp, .data$season_type == .env$season_type)
4347
if (nrow(pbp) == 0){
@@ -105,9 +109,10 @@ calculate_stats <- function(seasons = nflreadr::most_recent_season(),
105109
# we need those to identify things like fumbles depending on playtype or
106110
# first downs depending on playtype
107111
playstats <- load_playstats(seasons = seasons) %>%
108-
# if season_type is REG or POST, we filter pbp.
109-
# That's why we have to filter playstats as well
110-
dplyr::filter(.data$game_id %in% pbp$game_id) %>%
112+
# apply filtering on play stats so that it matches pbp, e.g.
113+
# - game filters for REG/POST
114+
# - only plays included in pbp in case it was provided manually
115+
dplyr::semi_join(pbp, by = c("game_id", "play_id")) %>%
111116
dplyr::rename("player_id" = "gsis_player_id", "team" = "team_abbr") %>%
112117
dplyr::group_by(.data$season, .data$week, .data$play_id, .data$player_id) %>%
113118
dplyr::mutate(
@@ -448,6 +453,8 @@ calculate_stats <- function(seasons = nflreadr::most_recent_season(),
448453
)
449454
}
450455

456+
if (custom_pbp) attr(stats, "custom_pbp") <- TRUE
457+
451458
stats
452459
}
453460

0 commit comments

Comments
 (0)