|
31 | 31 | calculate_stats <- function(seasons = nflreadr::most_recent_season(),
|
32 | 32 | summary_level = c("season", "week"),
|
33 | 33 | stat_type = c("player", "team"),
|
34 |
| - season_type = c("REG", "POST", "REG+POST")){ |
| 34 | + season_type = c("REG", "POST", "REG+POST"), |
| 35 | + pbp = NULL){ |
35 | 36 |
|
36 | 37 | summary_level <- rlang::arg_match(summary_level)
|
37 | 38 | stat_type <- rlang::arg_match(stat_type)
|
38 | 39 | 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) |
39 | 44 |
|
40 |
| - pbp <- nflreadr::load_pbp(seasons = seasons) |
41 | 45 | if (season_type %in% c("REG", "POST") && summary_level == "season") {
|
42 | 46 | pbp <- dplyr::filter(pbp, .data$season_type == .env$season_type)
|
43 | 47 | if (nrow(pbp) == 0){
|
@@ -105,9 +109,10 @@ calculate_stats <- function(seasons = nflreadr::most_recent_season(),
|
105 | 109 | # we need those to identify things like fumbles depending on playtype or
|
106 | 110 | # first downs depending on playtype
|
107 | 111 | 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")) %>% |
111 | 116 | dplyr::rename("player_id" = "gsis_player_id", "team" = "team_abbr") %>%
|
112 | 117 | dplyr::group_by(.data$season, .data$week, .data$play_id, .data$player_id) %>%
|
113 | 118 | dplyr::mutate(
|
@@ -448,6 +453,8 @@ calculate_stats <- function(seasons = nflreadr::most_recent_season(),
|
448 | 453 | )
|
449 | 454 | }
|
450 | 455 |
|
| 456 | + if (custom_pbp) attr(stats, "custom_pbp") <- TRUE |
| 457 | + |
451 | 458 | stats
|
452 | 459 | }
|
453 | 460 |
|
|
0 commit comments