#' Function to return all games a team on a team's schedule during a specified date range and their scores.
#'
#' @param team team identifier, either name, id, or abbreviation.
#' @param start_date beginning of date range to look
#' @param end_date end of date range to look
#'
#' @import jsonlite
#' @export
#'
#' @examples
#' buf_20182019 <- nhl_get_team_games(team = 'buf', start_date = '2018-09-01', end_date = '2019-06-01')
nhl_get_team_games <- function(team, start_date = Sys.Date(),
end_date = Sys.Date()) {
# 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)
}
# Get all data
schedule <- fromJSON(
paste0("https://statsapi.web.nhl.com/api/v1/schedule?teamId=", team_id,
"&startDate=", start_date,
"&endDate=", end_date))
# Process
game_date <- schedule$dates$date
ngames <- length(game_date)
away_team <- vector('character', ngames)
home_team <- vector('character', ngames)
away_score <- vector('integer', ngames)
home_score <- vector('integer', ngames)
season <- vector('character', ngames)
gametype <- vector('character', ngames)
gameid <- vector('character', ngames)
for(i in seq_along(game_date)) {
away_team[i] <- schedule$dates$games[[i]]$teams$away$team$name
away_score[i] <- schedule$dates$games[[i]]$teams$away$score
home_team[i] <- schedule$dates$games[[i]]$teams$home$team$name
home_score[i] <- schedule$dates$games[[i]]$teams$home$score
season[i] <- schedule$dates$games[[i]]$season
gametype[i] <- schedule$dates$games[[i]]$gameType
gameid[i] <- schedule$dates$games[[i]]$gamePk
}
# Return data frame
out <- data.frame(home_team, away_team,
away_score, home_score,
game_date, season, gametype, gameid)
out$winner <- ifelse(home_score > away_score, home_team, away_team)
return(out)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.