R/nhl_get_player_stats.R

Defines functions nhl_get_players nhl_get_players_base nhl_get_player_stats nhl_get_all_player_stats

Documented in nhl_get_players

#' Function to return a list of all players and goals on specified teams in a specified season, along with #' details and summary statistics.
#'
#' @param teams a vector of team identifiers, either name, id, or abbreviation.
#' @param season season (e.g. 20052006).  defaults to current season.
#'
#' @export
#'
#' @examples
#' buf_and_nyi <- nhl_get_players(teams = c('buf', 'nyi'))
#'
#' head(buf_and_nyi$goalies)
#' head(buf_and_nyi$players)
#'
#' buf_and_nyi_06 <- nhl_get_players(teams = c('buf', 'nyi'), season = 20062007)
#'
#' head(buf_and_nyi_06$goalies)
#' head(buf_and_nyi_06$players)
#'

nhl_get_players <- function(teams = NULL, season = get_this_season()) {
  # Get team id
  the_teams <- nhl_get_teams()
  if(!is.null(teams)) {
    team_ids <- NULL
    for(i in seq_along(teams)) {
      if(teams[i] %in% the_teams$id) {
        team_ids[i] <- teams[i]
      } else {
        type <- nhl_get_team_id_type(teams[i], teams = the_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_ids[i] <- get_id(x = teams[i], type = type, teams = the_teams)
      }
    }
  }
  # Get players
  all_players <- nhl_get_players_base(team_ids = team_ids, season = season)
  # Get player stats
  all_player_stats <- nhl_get_all_player_stats(all_players = all_players, season = season)
  # Goalies
  goalies <- merge(all_players[all_players$type == "Goalie", ],
                   all_player_stats$goalies, by = 'id')
  # Players
  players <- merge(all_players[all_players$type != "Goalie", ],
                   all_player_stats$players, by = 'id')
  return(list(
    'players' = players,
    'goalies' = goalies
  ))
}


### Internal helper functions ####

# Return all players and goals on a team in a season
nhl_get_players_base <- function(team_ids = NULL, season = season) {
  if(is.null(team_ids)) {
    team_ids <- paste(teams$id, collapse = ",")
  } else {
    team_ids <- paste(team_ids, collapse = ",")
  }
  players <- fromJSON(
    paste0("https://statsapi.web.nhl.com/api/v1/teams/?teamId=", team_ids,
           "&expand=team.roster&season=", season)
  )
  team_players <- list()
  team_positions <- list()
  team <- list()
  for(i in seq_along(players$teams$roster$roster)) {
    team_players[[i]] <- players$teams$roster$roster[[i]]$person[, c('id', 'fullName')]
    team_positions[[i]] <- players$teams$roster$roster[[i]]$position[, c('name', 'type')]
    team[[i]] <- rep(players$teams$teamName[i], length(team_positions[[i]]$name))
  }
  all_players <- cbind(
    do.call(rbind, team_players),
    do.call(rbind, team_positions),
    team = unlist(team))
  return(all_players)
}

# Return stats for a single player in a single season
nhl_get_player_stats <- function(player_id, season = get_this_season(),
                                 stats = 'all') {
  raw <- fromJSON(
    paste0("https://statsapi.web.nhl.com/api/v1/people/", player_id,
           "/stats/?stats=statsSingleSeason&season=", season)
  )
  out <- raw$stats$splits[[1]]$stat
  if(stats != 'all') {
    out <- out[, c(stats)]
  }
  return(out)
}

# Return stats for players in a season
nhl_get_all_player_stats <- function(all_players, season = get_this_season()) {
  player_stats <- vector('list', length(all_players$id[all_players$type != "Goalie"]))
  goalie_stats <- vector('list', length(all_players$id[all_players$type == "Goalie"]))
  tryCatch({
    for(i in seq_along(all_players$id[all_players$type != "Goalie"])) {
      player_stats[[i]] <- nhl_get_player_stats(player_id = all_players$id[all_players$type != "Goalie"][i],
                                                season = season)
      if(!is.null(player_stats[[i]])) {
        player_stats[[i]]$id <- all_players$id[all_players$type != "Goalie"][i]
      }
    }}, error = function(e) print("some player stats may be missing"))
  tryCatch({
    for(i in seq_along(all_players$id[all_players$type == "Goalie"])) {
      goalie_stats[[i]] <- nhl_get_player_stats(player_id = all_players$id[all_players$type == "Goalie"][i],
                                                season = season)
      if(!is.null(goalie_stats[[i]])) {
        goalie_stats[[i]]$id <- all_players$id[all_players$type == "Goalie"][i]
      }
    }}, error = function(e) print('some goalie stats may be missing')
  )
  all_player_stats <- do.call(rbind, player_stats)
  all_goalie_stats <- do.call(rbind, goalie_stats)
  return(
    list('players' = all_player_stats, 'goalies' = all_goalie_stats)
  )
}
alexpavlakis/nhl documentation built on May 18, 2019, 2:35 p.m.