R/nhl_get_team_stats.R

Defines functions nhl_get_team_stats

Documented in nhl_get_team_stats

#' Function to return stats for a team and a season
#'
#' @param team team identifier, either name, id, or abbreviation.
#' @param season vector of seasons (e.g. 20052006).  defaults to current season.
#' @import jsonlite
#'
#' @export
#'
#' @examples
#' buf_06 <- nhl_get_team_stats(team = 'Buffalo Sabres', season = 20062007)
#'
#' head(buf_06$stats)
#' head(buf_06$ranks)
#'
#' seasons <- paste0(seq(1990, 2018, 1), seq(1991, 2019, 1))
#' buf_all <- nhl_get_team_stats(team = 'Buffalo Sabres', season = seasons)
#' buf_all$ranks

# Get overall stats for a team and a season
nhl_get_team_stats <- function(team, season = get_this_season()) {

  # Get team id
  teams <- nhl_get_teams()
  if(team %in% teams$id) {
    team_id <- team
  } else {
    type <- nhl_get_team_id_type(team, teams)
    if(is.null(type)) {
      stop("please enter a valid team by either name (e.g. 'Sabres'),
           full name (e.g. 'Buffalo Sabres'), abbreviation (e.g. 'BUF'), or id (e.g. 7)")
    }
    team_id <- get_id(x = team, type = type, teams)
  }

  # Drop lockout year
  if(length(season) == 1) {
    if(season == "20042005") {
      stop("The 2004–05 NHL lockout was a lockout that resulted in the cancellation of what would have been the 88th season of play of the National Hockey League (NHL).")
    }
  }
  if("20042005" %in% season) {
    cat('no data for 2004-2005 season due to lockout.')
    season <- season[-which(season == "20042005")]
  }

  # Get history
  stats <- list()
  ranks <- list()
  history <- list()
  for(i in seq_along(season)) {
    history[[i]] <- fromJSON(
      paste0("https://statsapi.web.nhl.com/api/v1/teams/", team_id,
             "?expand=team.stats&season=", season[i]))
    stats[[i]] <- data.frame(history[[i]]$teams$teamStats[[1]]$splits[[1]]$stat[1, ])
    ranks[[i]] <- data.frame(history[[i]]$teams$teamStats[[1]]$splits[[1]]$stat[2, ])
  }
  stats_out <- do.call(rbind, stats)
  stats_out$season <- season
  ranks_out <- do.call(rbind, ranks)
  ranks_out$season <- season
  out <- list(stats = stats_out,
              ranks = ranks_out,
              raw = history)
  return(out)
}
alexpavlakis/nhl documentation built on May 18, 2019, 2:35 p.m.