Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:A Minimum-Dependency 'R' Interface to the 'NHL' API
Version:0.1.4
Maintainer:Jozef Hajnala <jozef.hajnala@gmail.com>
Description:Retrieves and processes the data exposed by the open 'NHL' API. This includes information on players, teams, games, tournaments, drafts, standings, schedules and other endpoints. A lower-level interface to access the data via URLs directly is also provided.
Depends:R (≥ 2.10)
Imports:jsonlite
Encoding:UTF-8
LazyData:true
RoxygenNote:7.1.1
Suggests:testthat, roxygen2, knitr, rmarkdown
License:AGPL-3
Language:en-US
URL:https://github.com/jozefhajnala/nhlapi
BugReports:https://github.com/jozefhajnala/nhlapi/issues
VignetteBuilder:knitr
SysDataCompression:xz
Copyright:NHL and the NHL Shield are registered trademarks of theNational Hockey League. NHL and NHL team marks are the propertyof the NHL and its teams.
NeedsCompilation:no
Packaged:2021-02-19 14:18:47 UTC; root
Author:Jozef Hajnala [aut, cre]
Repository:CRAN
Date/Publication:2021-02-20 01:20:05 UTC

Create a log message

Description

Create a log message

Usage

make_log(  msg,  ...,  type = "I",  dtFormat = getOption("nhlapi_log_datetime"),  newLine = FALSE,  sep = " | ",  collapse = " ",  lineBreak = "$",  endNewLine = FALSE)

Arguments

msg

character(1), to be logged.

...

additionalcharacter() strings to be logged. Will bepasted tomsg and collapsed using thecollapse argument.

type

character(1) ideally 1 uppercase letter.

dtFormat

character(1), passed to format for⁠[Sys.time()]⁠

newLine

logical(1), ifTRUE, new line will be pasted.to the beginning of the message.

sep

⁠character(1) string⁠, to separate parts of the message.

collapse

character(1), to collapsemsg and....

lineBreak

character(1), replacing line breaks inmsg.

endNewLine

logical(1), ifTRUE, new line will bepasted to the end of the message.

Value

character(1), constructed log message.

Examples

  nhlapi:::make_log("Dummy warning", type = "W")

Retrieve metadata on NHL awards from the API

Description

Retrieve metadata on NHL awards from the API

Usage

nhl_awards(awardIds = NULL)

Arguments

awardIds

integer(), vector of one or more award idsorNULL (default) for all awards. The current set of validids seems to be1:24.

Value

data.frame, with information on awards, one row per award.

Examples

## Not run:   # Get information on all awards  nhl_awards()  # Get information on 3 historical awards  nhl_awards(1:3)## End(Not run)

Retrieve metadata on NHL conferences from the API

Description

Retrieve metadata on NHL conferences from the API

Usage

nhl_conferences(conferenceIds = NULL)

Arguments

conferenceIds

integer(), ids of the conferences orNULL(default) for all conferences As of end of 2019, the validconference ids seem to be in the1:7 range.

Value

data.frame, with information on conferences, one rowper conference.

Examples

## Not run:   # Get information on all conferences  nhl_conferences()  # Get information on 2 selected conferences  nhl_conferences(5:6)## End(Not run)

Retrieve metadata on NHL divisions from the API

Description

Retrieve metadata on NHL divisions from the API

Usage

nhl_divisions(divisionIds = NULL)

Arguments

divisionIds

integer(), ids of the divisions orNULL(default) for all divisions. As of end of 2019, the validdivision ids seem to be in the1:25 range.

Value

data.frame, with information on divisions, one rowper division.

Examples

## Not run:   # Get information on all divisions  nhl_divisions()  # Get information on 2 selected divisions  nhl_divisions(15:16)## End(Not run)

Retrieve metadata on NHL draft prospects from the API

Description

Retrieve metadata on NHL draft prospects from the API

Usage

nhl_draft_prospects(prospectIds = NULL)

Arguments

prospectIds

integer(), vector of one or more ids ofdraft prospects orNULL (default) for all exposed prospects.

Value

data.frame, with information on draft prospects, one rowper draft prospect.

Examples

## Not run:   # Get information on current draft prospects  nhl_draft_prospects()## End(Not run)

Retrieve metadata on NHL drafts from the API

Description

Retrieve metadata on NHL drafts from the API

Usage

nhl_drafts(draftYears = NULL)

Arguments

draftYears

integer(), vector of one or more years inYYYY format orNULL (default) for the current year's draft.Also accepts a character vector of years inYYYY format.

Value

data.frame, with information on drafts, one rowper draft year.

Examples

## Not run:   # Get information on current draft  nhl_drafts()  # Get information on 3 historical drafts  nhl_drafts(2015:2017)## End(Not run)

Get URL usingfromJSON

Description

Get URL usingfromJSON

Usage

nhl_from_json(  url,  flatten = getOption("nhlapi_flatten"),  silent = getOption("nhlapi_try_silent"),  retries = getOption("nhlapi_get_retries"),  retrySleep = getOption("nhlapi_get_retry_sleep"),  noRetryPatt = getOption("nhlapi_get_noretry"))

Arguments

url

character(1), the URL to get the data from.

flatten

logical(1), ifTRUE (default) automaticallyflattens nested data frames into a single non-nested data frame.

silent

logical(1), passed to⁠[try()]⁠.

retries

integer(1), number of retries in case of faileddata retrieval (0L for no no retries).

retrySleep

integer(1), number of seconds to⁠[Sys.sleep()]⁠ in between retries.

noRetryPatt

character(1), string pattern. If the errorcondition's message contains this pattern, there will be noretries. Useful for e.g.404 returns where retries are likelyuseless.

Value

list, retrieved data if succeeded, atry-error classobject otherwise.


Retrieve metadata on NHL games from the API

Description

Retrieve metadata on NHL games from the API

Usage

nhl_games(gameIds, element)nhl_games_content(gameIds)nhl_games_feed(gameIds)nhl_games_boxscore(gameIds)nhl_games_linescore(gameIds)

Arguments

gameIds

numeric(), vector of one or more game ids. Thegame id is a 10 digit number where the

  • first 4 digits identify the season of the game, for instance2017 for the 2017-2018 season.

  • next 2 digits give the type of game, where

    • 01 - preseason,

    • 02 - regular season,

    • 03 - playoffs,

    • 04 - all-star.

  • final 4 digits identify the specific game number

    • for regular season and preseason games, this ranges from0001 to the number of games played. That is 1271 forseasons with 31 teams and 1230 for seasons with 30 teams.

    • for playoff games, the

      • second digit gives the round of the playoffs

      • third digit specifies the match-up

      • fourth digit specifies the game (out of 7)

element

character() vector of one or more valid elements.Currently the valid elements seem to be:

  • "linescore"

  • "boxscore"

  • "content"

  • "feed/live"

Value

list, with information on games, one element per gameand element combination.

Functions

Examples

## Not run:   # Get content for one game  nhl_games(2017010001, "content")  # Get both box score and content for 2 games  nhl_games(c(2017010001, 2017010002), c("content", "boxscore"))  # Get content for a game  nhl_games_content(2017010001)  # Get the game feed for a game  nhl_games_feed(2017010001)  # Get the box score for a game  nhl_games_boxscore(2017010001)  # Get the line score for a game  nhl_games_linescore(2017010001)## End(Not run)

Get data from the API for one or more URLs

Description

Get data from the API for one or more URLs

Usage

nhl_get_data(urls, flatten = getOption("nhlapi_flatten"))

Arguments

urls

character(), vector of URLs to retrievethe data from.

flatten

logical(1), ifTRUE (default) automaticallyflattens nested data frames into a single non-nested data frame.

Value

list, results retrieved usingnhl_get_data_worker().One element per url. The elements contain the retrieved dataif retrieval succeeded, otherwise annhl_get_data_error classobject.

See Also

nhl_get_data_worker()

Examples

## Not run:   nhl_get_data(c(    "https://statsapi.web.nhl.com/api/v1/teams/1",    "https://statsapi.web.nhl.com/api/v1/people/8477474"  ))  nhl_get_data(    "https://statsapi.web.nhl.com/api/v1/teams/1",    flatten = FALSE  )## End(Not run)

Get data from the API for 1 URL

Description

Gets data from the NHL API usingnhl_from_json().

Usage

nhl_get_data_worker(  url,  flatten = getOption("nhlapi_flatten"),  silent = getOption("nhlapi_try_silent"),  retries = getOption("nhlapi_get_retries"),  retrySleep = getOption("nhlapi_get_retry_sleep"))

Arguments

url

character(1), the URL to get the data from.

flatten

logical(1), ifTRUE (default) automaticallyflattens nested data frames into a single non-nested data frame.

silent

logical(1), passed to⁠[try()]⁠.

retries

integer(1), number of retries in case of faileddata retrieval (0L for no no retries).

retrySleep

integer(1), number of seconds to⁠[Sys.sleep()]⁠ in between retries.

Value

list, with the retrieved data or classnhl_get_data_error.

See Also

nhl_from_json(),nhl_url()


Make a vector of seasons consumable by the API

Description

The NHL API wants seasons defined in format"YYYYZZZZ" whereZZZZ = YYYY + 1. This is a helper to takea vector of years in"YYYY" format and create a vector ofsuch seasons to be used with the API.

Usage

nhl_make_seasons(seasons = 1950:2019)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

Value

character(), vector of seasons suited for the NHL API.

Examples

  nhlapi:::nhl_make_seasons()  nhlapi:::nhl_make_seasons(1995:2000)  nhlapi:::nhl_make_seasons(c(1995, 2015))  nhlapi:::nhl_make_seasons(c("1995", "2015"))

Get event types metadata

Description

Get event types metadata

Usage

nhl_md_event_types()

Value

list, with metadata on event types.


Get game status metadata

Description

Get game status metadata

Usage

nhl_md_game_statuses()

Value

list, with metadata on game statuses.


Get game type metadata

Description

Get game type metadata

Usage

nhl_md_game_types()

Value

list, with metadata on game types.


Get play types metadata

Description

Get play types metadata

Usage

nhl_md_play_types()

Value

list, with metadata on play types.


Get standings types metadata

Description

Get standings types metadata

Usage

nhl_md_standings_types()

Value

list, with metadata on standings types.


Get stat types metadata

Description

Get stat types metadata

Usage

nhl_md_stat_types()

Value

list, with metadata on stat types.


Get tournament types metadata

Description

Get tournament types metadata

Usage

nhl_md_tournament_types()

Value

list, with metadata on tournament types.


Retrieve metadata for players based on names or ids

Description

Retrieves information on players from the NHL API based onplayerNames orplayerIds. IfplayerNames are provided,they take precedence overplayerIds.

Usage

nhl_players(playerNames, playerIds = NULL)

Arguments

playerNames

character(), vector of one or more player names.Not case sensitive for convenience.

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

Value

data.frame, with information on selected players.

Examples

## Not run:  # With player names nhl_players(c("joe SAKIC", "patrick roy")) # With playerIds nhl_players(playerIds = c(8451101, 8458554))## End(Not run)

Retrieve all seasons statistics for players

Description

Retrieve all seasons statistics for players

Usage

nhl_players_allseasons(playerNames, playerIds = NULL)

Arguments

playerNames

character(), vector of one or more player names.Not case sensitive for convenience.

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

Value

data.frame, with all season statistics forselected players.

Examples

## Not run:  # With player names nhl_players_allseasons(c("joe sakic", "Peter Forsberg")) # With player ids nhl_players_allseasons(c(8451101, 8458554))## End(Not run)

Retrieve selected seasons statistics for players

Description

Retrieve selected seasons statistics for players

Usage

nhl_players_seasons(playerNames, seasons, playerIds = NULL, playoffs = FALSE)

Arguments

playerNames

character(), vector of one or more player names.Not case sensitive for convenience.

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

playoffs

logical(1), ifFALSE (default) get the regularseasons data, ifTRUE, get the data for the playoffs.

Value

data.frame, with selected season statisticsfor selected players.

Examples

## Not run:  nhl_players_seasons(   playerIds = c(8451101, 8458554),   seasons = "19951996",   playoffs = TRUE )## End(Not run)

Plot an NHL rink

Description

Initialize a plot in base graphics witha to-scale NHL rink as the background

Usage

nhl_plot_rink()

Details

The placement of rink features & their sizesare exact according to the NHL rule book; see citation.

Examples

## Not run:   # Retrieve some game feed data  gameFeeds <- lapply(   2019010001:2019010010,   nhlapi::nhl_games_feed  )  # Create a data.frame with plays  getPlaysDf <- function(gm) {    playsRes <- try(gm[[1L]][["liveData"]][["plays"]][["allPlays"]])    if (inherits(playsRes, "try-error")) data.frame() else playsRes  }  plays <- lapply(gameFeeds, getPlaysDf)  plays <- nhlapi:::util_rbindlist(plays)  plays <- plays[!is.na(plays$coordinates.x), ]  # Move the coordinates to non-negative values before plotting  plays$coordx <- plays$coordinates.x + abs(min(plays$coordinates.x))  plays$coordy <- plays$coordinates.y + abs(min(plays$coordinates.y))  # Select goals only  goals <- plays[plays$result.event == "Goal", ]  # Create the plot and add goals  nhlapi::plot_rink()  points(goals$coordinates.x, goals$coordinates.y)## End(Not run)

Retrieve metadata on NHL schedule from the API

Description

The general-purposenhl_schedule() exposes many parameters,some useful helpers are exposed as separate functions toreflect common use cases. Arguments can be passed to thesenamed via....

Usage

nhl_schedule(  seasons = NULL,  teamIds = NULL,  startDate = NULL,  endDate = NULL,  gameTypes = NULL,  expand = NULL)nhl_schedule_today(...)nhl_schedule_seasons(seasons, ...)nhl_schedule_date_range(startDate, endDate, ...)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

startDate

character(1), date in the format"YYYY-MM-DD"defining the start of the date interval for which the schedule isto be retrieved.

endDate

character(1), date in the format"YYYY-MM-DD"defining the end of the date interval for which the schedule isto be retrieved.

gameTypes

character(), defining the game types to retrieve.Valid game types are for example"R" for regular season or"P"for playoffs. Seenhl_md_game_types() for all values and theirdescriptions.

expand

character(), of parameters passed asexpandto the API URL. Some valid examples seem to be"round.series"and"schedule.broadcasts","schedule.linescore","schedule.ticket".NULL for no expand parameter.

...

other named parameters passed tonhl_schedule().

Value

list, with information on schedule, depending onprovided arguments.

Functions

Examples

## Not run:  # Get current schedule nhl_schedule() # Get schedule for historical seasons nhl_schedule(seasons = 2015:2016) # Get schedule for a date range nhl_schedule(startDate = "2018-01-02", endDate = "2018-01-02") # Get schedule for a date range, specific teams # and expand on line scores nhl_schedule(   startDate = "2018-01-02",   endDate = "2018-01-02",   teamIds = c(29, 30),   expand = "schedule.linescore" )## End(Not run)## Not run:   nhl_schedule_today()## End(Not run)## Not run:   # Schedule for seasons starting in 2015 and 2016  nhl_schedule_seasons(2015:2016)  # Schedule for seasons starting in 2015 and 2016  # Only 1 team and expand line scores  nhl_schedule_seasons(    2015:2016,    teamIds = 1,    expand = "schedule.linescore"  )## End(Not run)## Not run:   # Schedule for October and November 2015  nhl_schedule_date_range(    startDate = "2015-10-01",    endDate = "2015-11-30"  )  # Schedule for October and November 2015  # Regular seasons only, specific team and expand line scores  nhl_schedule_date_range(    startDate = "2015-10-01", endDate = "2015-11-30",    gameTypes = "R",    teamIds = 2,    expand = "schedule.linescore"  )## End(Not run)

Retrieve metadata on NHL seasons from the API

Description

Retrieve metadata on NHL seasons from the API

Usage

nhl_seasons(seasons = NULL)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

Value

data.frame, with information on seasons, one rowper year.

Examples

## Not run:   # Get information on all seasons  nhl_seasons()  # Get information on 3 historical seasons  nhl_seasons(2015:2017)## End(Not run)

Retrieve metadata on NHL standings from the API

Description

Retrieve metadata on NHL standings from the API

Usage

nhl_standings(seasons = NULL, standingsTypes = NULL, expand = NULL)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

standingsTypes

character(), defining the standingstypes to retrieve. Valid standings types are for example"regularSeason" or"byDivision". Seenhl_md_standings_types() for all values and theirdescriptions.

expand

character(), of parameters passed asexpandto the API URL. A valid example seems to be"standings.record".NULL for no expand parameter.

Value

list, with information on standingsdepending on provided arguments.

Examples

## Not run:  # Get current standings nhl_standings() # Get standings for historical seasons nhl_standings(seasons = 2015:2016) # Get standings for historical seasons nhl_standings(   seasons = 2015:2016,   standingsType = "byDivision",   expand = "standings.record" )## End(Not run)

Retrieve metadata on NHL teams from the API

Description

Retrieves team metadata such as the teams names,abbreviations, locations, conferences, venues, etc.

Usage

nhl_teams(teamIds = NULL, params = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

params

⁠named list()⁠, further parameters passed tonhl_url_teams.

Details

The API allows to retrieve data on all teams at once,which is achieved by the defaultNULL value for the team id.

Value

data.frame, with data on teams, one row per team.

Examples

## Not run:   nhl_teams()  nhl_teams(1:3)## End(Not run)

Get rosters for teams

Description

Get rosters for teams

Usage

nhl_teams_rosters(teamIds = NULL, seasons = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

Value

data.frame, with an element calledroster.rosterthat in itself is adata.frame with the roster data.

Examples

 ## Not run:   # Current rosters for all teams  nhl_teams_rosters()  # Rosters for all teams for past seasons  nhl_teams_rosters(seasons = c("19931994", "19931994"))  # Roster for Devils and Islanders  nhl_teams_rosters(    teamIds = 1:2,    seasons = c("19931994", "19931994")  )## End(Not run)

Get details for the teams' upcoming game

Description

Get details for the teams' upcoming game

Usage

nhl_teams_shedule_next(teamIds = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

Value

data.frame, with elements with names starting withnextGameSchedule that contain data on the teams' upcominggame. One row per team.

Examples

 ## Not run:   # Next game for all teams  nhl_teams_shedule_next()  # Next game for selected teams  nhl_teams_shedule_next(c(1,3,5))## End(Not run)

Get details for the teams' previous game

Description

Get details for the teams' previous game

Usage

nhl_teams_shedule_previous(teamIds = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

Value

data.frame, with elements with names starting withpreviousGameSchedule that contain data on the teams'previous game. One row per team.

Examples

 ## Not run:   # Next game for all teams  nhl_teams_shedule_previous()  # Next game for selected teams  nhl_teams_shedule_previous(c(1,3,5))## End(Not run)

Get team statistics per seasons

Description

Get team statistics per seasons

Usage

nhl_teams_stats(teamIds = NULL, seasons = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

Value

data.frame, with seasons statistics for the selectedteam(s), one row per each team and season combination.

Examples

## Not run:   # All teams, current seasons  nhl_teams_stats()  # 2 teams, 3 seasons  nhl_teams_stats(1:2, c("20052006", "20062007", "20072008"))## End(Not run)

Retrieve data on tournaments from the API

Description

Retrieve data on tournaments from the API

Usage

nhl_tournaments(tournamentTypes, seasons = NULL, expand = NULL)nhl_tournaments_playoffs(seasons = NULL, expand = NULL)nhl_tournaments_olympics(seasons = NULL, expand = NULL)nhl_tournaments_worldcups(seasons = NULL, expand = NULL)

Arguments

tournamentTypes

character(), vector of one or moretournament types. Currently supported types seem to be

  • "playoffs"

  • "olympics"

  • "worldCup"

Those are exposed via shorthand functions

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

expand

character(), of parameters passed asexpandto the API URL. Two valid examples seem to be"round.series"and"schedule.game.seriesSummary".NULL for no expandparameter.

Value

list, with information on tournaments, one element pertournamentTypes and parameters (seasons andexpand)combinations.

Functions

Examples

## Not run:   # Get info on playoffs in one season  nhl_tournaments("playoffs", 2015)  # Get info on playoffs in 2 seasons, expand rounds  nhl_tournaments("playoffs", 2015:2016, "round.series")## End(Not run)## Not run:   nhl_tournaments_playoffs(2015:2016, "round.series")## End(Not run)## Not run:   nhl_tournaments_olympics(2009, "round.series")## End(Not run)## Not run:   nhl_tournaments_worldcups(2003)## End(Not run)

Create an NHL API URL

Description

Create an NHL API URL

Usage

nhl_url(  endPoint = NULL,  suffixes = NULL,  params = NULL,  baseUrl = getOption("nhlapi_baseurl"))

Arguments

endPoint

character(1), the API endpoint.

suffixes

list(), of suffixes that will beconcatenated to the end of the URLs, separated by/.

params

⁠named list()⁠ of parameters that will beconcatenated to the end of the URLs after⁠?⁠. Parameterscan have multiple values, in which case multiple URLsare created. Multiple parameters are separated by&.

baseUrl

character(1), URL of the NHL API base location.

Value

character(), the created URLs.

Examples

  nhlapi:::nhl_url("people", "8477474")

Add parameters to URLs

Description

Add parameters to URLs

Usage

nhl_url_add_params(url, params = NULL)

Arguments

url

character(), vector of URLs.

params

⁠named list()⁠ of parameters that will beconcatenated to the end of the URLs after⁠?⁠. Parameterscan have multiple values, in which case multiple URLsare created. Multiple parameters are separated by&.

Value

character(), URLs with parameters added. Samelength as all the combinations ofurl andparams.


Add suffixes to URLs

Description

Add suffixes to URLs

Usage

nhl_url_add_suffixes(url, suffixes)

Arguments

url

character(), vector of URLs.

suffixes

list(), of suffixes that will beconcatenated to the end of the URLs, separated by/.

Value

character(), URLs with suffixes added. Samelength as all the combinations ofurl andsuffixes.


Create an NHL API URL for awards

Description

Create an NHL API URL for awards

Usage

nhl_url_awards(awardIds = NULL)

Arguments

awardIds

integer(), vector of one or more award idsorNULL (default) for all awards. The current set of validids seems to be1:24.

Value

character(), API URLs, same length asawardIds orlength1 ifawardIds isNULL.

Examples

  nhlapi:::nhl_url_awards()  nhlapi:::nhl_url_awards(1:3)

Create an NHL API URL for conferences

Description

Create an NHL API URL for conferences

Usage

nhl_url_conferences(conferenceIds = NULL)

Arguments

conferenceIds

integer(), ids of the conferences orNULL(default) for all conferences As of end of 2019, the validconference ids seem to be in the1:7 range.

Value

character(), API URLs, same length asteamIds orlength1 ifteamIds isNULL.

Examples

  nhlapi:::nhl_url_conferences()  nhlapi:::nhl_url_conferences(1:3)

Create an NHL API URL for divisions

Description

Create an NHL API URL for divisions

Usage

nhl_url_divisions(divisionIds = NULL)

Arguments

divisionIds

integer(), ids of the divisions orNULL(default) for all divisions. As of end of 2019, the validdivision ids seem to be in the1:25 range.

Value

character(), of same length asteamIds or length1 ifteamIds isNULL.

Examples

  nhlapi:::nhl_url_divisions()  nhlapi:::nhl_url_divisions(1:3)

Create an NHL API URL for draft prospects

Description

Create an NHL API URL for draft prospects

Usage

nhl_url_draft_prospects(prospectIds = NULL)

Arguments

prospectIds

integer(), vector of one or more ids ofdraft prospects orNULL (default) for all exposed prospects.

Value

character(), API URLs, same length asprospectIds orlength1 ifprospectIds isNULL.

Examples

  nhlapi:::nhl_url_draft_prospects()

Create an NHL API URL for drafts

Description

Create an NHL API URL for drafts

Usage

nhl_url_drafts(draftYears = NULL)

Arguments

draftYears

integer(), vector of one or more years inYYYY format orNULL (default) for the current year's draft.Also accepts a character vector of years inYYYY format.

Value

character(), API URLs, same length asdraftYears orlength1 ifdraftYears isNULL.

Examples

  nhlapi:::nhl_url_drafts()  nhlapi:::nhl_url_drafts(2015:2017)

Create an NHL API URL for games

Description

Create an NHL API URL for games

Usage

nhl_url_games(gameIds, element)

Arguments

gameIds

numeric(), vector of one or more game ids. Thegame id is a 10 digit number where the

  • first 4 digits identify the season of the game, for instance2017 for the 2017-2018 season.

  • next 2 digits give the type of game, where

    • 01 - preseason,

    • 02 - regular season,

    • 03 - playoffs,

    • 04 - all-star.

  • final 4 digits identify the specific game number

    • for regular season and preseason games, this ranges from0001 to the number of games played. That is 1271 forseasons with 31 teams and 1230 for seasons with 30 teams.

    • for playoff games, the

      • second digit gives the round of the playoffs

      • third digit specifies the match-up

      • fourth digit specifies the game (out of 7)

element

character() vector of one or more valid elements.Currently the valid elements seem to be:

  • "linescore"

  • "boxscore"

  • "content"

  • "feed/live"

Value

character(), of same length asgameIds.

Examples

  nhlapi:::nhl_url_games(2017010001, "content")  nhlapi:::nhl_url_games(    c(2017010001, 2017010002),    c("content", "boxscore")  )

Create an NHL API URL for players

Description

Create an NHL API URL for players

Usage

nhl_url_players(playerIds)

Arguments

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

Value

character(), API URLs, same length asplayerIds.

Examples

  nhlapi:::nhl_url_players(playerIds = c(8477474, 8477475))

Create an NHL API URL for all players' seasons statistics

Description

Create an NHL API URL for all players' seasons statistics

Usage

nhl_url_players_allseasons(playerIds)

Arguments

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

Examples

  # Joe Sakic, all seasons  nhlapi:::nhl_url_players_allseasons(8451101L)

Create an NHL API URL for players' seasons statistics

Description

Create an NHL API URL for players' seasons statistics

Usage

nhl_url_players_seasons(playerIds, seasons, playoffs = FALSE)

Arguments

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

playoffs

logical(1), ifFALSE (default) get the regularseasons data, ifTRUE, get the data for the playoffs.

Details

If multiple players and seasons are provided, URLs willbe created for all combinations of players and seasons.

Examples

  # Joe Sakic, regular season 1995/1996  nhlapi:::nhl_url_players_seasons(8451101L, 1995)  # Joe Sakic, playoffs 1995/1996, 1996/1997 and 1997/1998  nhlapi:::nhl_url_players_seasons(    8451101L,    1995:1997,    playoffs = TRUE   )

Create an NHL API stats URL for players

Description

Create an NHL API stats URL for players

Usage

nhl_url_players_stats(playerIds, params = NULL)

Arguments

playerIds

integer(), vector of one or more ids of theplayers. The ids correspond to the ids expected by the NHLAPI people endpoint. For most cases theplayerNames argumentcan be provided for more convenient usage.

params

⁠named list()⁠ of parameters that will beconcatenated to the end of the URLs after⁠?⁠. Parameterscan have multiple values, in which case multiple URLsare created. Multiple parameters are separated by&.

Value

character(), of API URLs, same length asplayerIds.

Examples

  nhlapi:::nhl_url_players_stats(8477474)

Create an NHL API URL for schedules

Description

Create an NHL API URL for schedules

Usage

nhl_url_schedule(  seasons = NULL,  teamIds = NULL,  startDate = NULL,  endDate = NULL,  gameTypes = NULL,  expand = NULL)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

startDate

character(1), date in the format"YYYY-MM-DD"defining the start of the date interval for which the schedule isto be retrieved.

endDate

character(1), date in the format"YYYY-MM-DD"defining the end of the date interval for which the schedule isto be retrieved.

gameTypes

character(), defining the game types to retrieve.Valid game types are for example"R" for regular season or"P"for playoffs. Seenhl_md_game_types() for all values and theirdescriptions.

expand

character(), of parameters passed asexpandto the API URL. Some valid examples seem to be"round.series"and"schedule.broadcasts","schedule.linescore","schedule.ticket".NULL for no expand parameter.

Value

character(), vector of URLs.

Examples

 nhlapi:::nhl_url_schedule(seasons = 2015:2016) nhlapi:::nhl_url_schedule(   startDate = "2018-01-02",   endDate = "2018-01-02" ) nhlapi:::nhl_url_schedule(   startDate = "2018-01-02",   endDate = "2018-01-02",   teamIds = c(29, 30),   expand = "schedule.linescore" )

Create an NHL API URL for seasons

Description

Create an NHL API URL for seasons

Usage

nhl_url_seasons(seasons = NULL)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

Value

character(), of API URLs, same length asseasonsor length1 ifseasons isNULL.

Examples

  nhlapi:::nhl_url_seasons()  nhlapi:::nhl_url_seasons(2015:2017)  nhlapi:::nhl_url_seasons("20152016")

Create an NHL API URL for standings

Description

Create an NHL API URL for standings

Usage

nhl_url_standings(seasons = NULL, standingsTypes = NULL, expand = NULL)

Arguments

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

standingsTypes

character(), defining the standingstypes to retrieve. Valid standings types are for example"regularSeason" or"byDivision". Seenhl_md_standings_types() for all values and theirdescriptions.

expand

character(), of parameters passed asexpandto the API URL. A valid example seems to be"standings.record".NULL for no expand parameter.

Value

character(), vector of URLs.

Examples

 nhlapi:::nhl_url_standings(seasons = 2015:2016) nhlapi:::nhl_url_standings(   standingsType = "byDivision",   expand = "standings.record" )

Create an NHL API URL for teams

Description

Create an NHL API URL for teams

Usage

nhl_url_teams(teamIds = NULL, params = NULL)

Arguments

teamIds

integer(), ids of the teams orNULL (default)for all teams. As of end of 2019, the valid team ids seem to bein the1:54 range.

params

⁠named list()⁠ of parameters that will beconcatenated to the end of the URLs after⁠?⁠. Parameterscan have multiple values, in which case multiple URLsare created. Multiple parameters are separated by&.

Value

character(), API URLs, same length asteamIds orlength1 ifteamIds isNULL.

Examples

  nhlapi:::nhl_url_teams()  nhlapi:::nhl_url_teams(1:3)

Create an NHL API URL for tournaments

Description

Create an NHL API URL for tournaments

Usage

nhl_url_tournaments(tournamentTypes, seasons = NULL, expand = NULL)

Arguments

tournamentTypes

character(), vector of one or moretournament types. Currently supported types seem to be

  • "playoffs"

  • "olympics"

  • "worldCup"

Those are exposed via shorthand functions

seasons

numeric(),integer() orcharacter(),vector of starting years of desired seasons inYYYYformat, e.g.1995 or"1995" for season 1995-1996.Accepts vectors such asc(1995:2000, 2010) to generatemultiple seasons.

Alternatively, also acceptscharacter() with seasons in theformat"YYYYZZZZ", whereZZZZ = YYYY + 1, e.g."19951996".This is the format that ultimately gets sent to the NHL API.

Some API endpoints, notablyseasons exposed vianhl_seasons()also allow the value"current" to passed. This value will bereturned unchanged.

expand

character(), of parameters passed asexpandto the API URL. Two valid examples seem to be"round.series"and"schedule.game.seriesSummary".NULL for no expandparameter.

Value

character(), API URLs, same length as combinations oftournamentTypes,seasons andexpand.

See Also

nhl_md_tournament_types()

Examples

  nhlapi:::nhl_url_tournaments("olympics")  nhlapi:::nhl_url_tournaments("playoffs", 2015:2016)  nhlapi:::nhl_url_tournaments("playoffs", 2015:2016, "round.series")

Create an NHL API URL for venues

Description

Create an NHL API URL for venues

Usage

nhl_url_venues(venueIds = NULL)

Arguments

venueIds

integer(), vector of one or more venue idsorNULL (default) for all currently exposed venues. Theexported values seem incomplete, so it may be worth it toinvestigate other ids.

Value

character(), API URLs, same length asvenueIds orlength1 ifvenueIds isNULL.

Examples

  nhlapi:::nhl_url_venues()  nhlapi:::nhl_url_venues(5000:5006)

Retrieve metadata on NHL venues from the API

Description

Retrieve metadata on NHL venues from the API

Usage

nhl_venues(venueIds = NULL)

Arguments

venueIds

integer(), vector of one or more venue idsorNULL (default) for all currently exposed venues. Theexported values seem incomplete, so it may be worth it toinvestigate other ids.

Value

data.frame, with information on venues, one row per venue.

Examples

## Not run:   # Get information on currently exposed venues  nhl_venues()  # Get information on 3 historical venues  nhl_venues(5000:5006)## End(Not run)

Add attributes as data frame columns

Description

Take attributes with names specified byatrsfrom objectlst and adds their value into columns with the samename indf.

Usage

util_attributes_to_cols(lst, df, atrs = c("url", "copyright"))

Arguments

lst

list, with attributes to be added as columns todf.

df

data.frame, onto which new columns containing attributesoflst should be added.

atrs

character(), vector of names of attributesoflst.

Value

data.frame,df with added columns.


Convert"mm:ss" character to numeric minutes

Description

Convert"mm:ss" character to numeric minutes

Usage

util_convert_minsonice(chr, splitter = ":")

Arguments

chr

character(), vector in format"mins:secs".

splitter

character(1), that splitsminutes and seconds in elements ofchr.

Value

numeric(), vector of times in minutes. Same lengthaschr.

Examples

   nhlapi:::util_convert_minsonice(c("20:00", "1500:30"))

Generate thesysdata.rda file

Description

Generate thesysdata.rda file

Usage

util_generate_sysdata(playerIds = 8444849L:8490000L, tgtPath = "sysdata.rda")

Arguments

playerIds

integer(), vector ofplayerIds.

tgtPath

character(1), path where to savethe generated object,NULL to not save.

Value

data.frame, with player name hashes and ids.


Inherit attributes from another object

Description

Take attributes with names specified byatrsfrom objectsrc and add them as the same attributes totgt.

Usage

util_inherit_attributes(src, tgt, atrs = c("url", "copyright"))

Arguments

src

object, with attributes to be inherited bytgt.

tgt

object, onto which attributes ofsrc should be added.

atrs

character(), vector of names of attributesofsrc to be added totgt.

Value

object, same astgt with attributes added.


Retrieve a player id from the name

Description

Using a table of hashed names andids, get a player id based on the name.

Usage

util_map_player_id(x, map = getOption("nhlapi_player_map"))

Arguments

x

character(1) a player's name, not casesensitive for convenience.

map

data.frame, with 2 columns:

  • nameMd5:character() of hashed player names

  • id:integer() of player ids used by the NHL API

Value

integer(1), id of the player orNA_integerif not found.

Examples

  nhlapi:::util_map_player_id(   "Joe Sakic",   data.frame(     nameMd5 = "9d2a915c8610dbc524c1bc800e010fcc",     id = 19L,     stringsAsFactors = FALSE   ) )

Retrieve a player ids from their names

Description

Retrieve a player ids from their names

Usage

util_map_player_ids(playerNames, map = getOption("nhlapi_player_map"))

Arguments

playerNames

character(), vector of one or more player names.Not case sensitive for convenience.

map

data.frame, with 2 columns:

  • nameMd5:character() of hashed player names

  • id:integer() of player ids used by the NHL API

Value

integer(), named vector of player ids,'NA_integer“ for those names where id was notfound. In case a player name has multiple ids,all of them are returned.

Examples

  nhlapi:::util_map_player_ids(    c("Joe SAKIC", "peter Forsberg", "test")  )

Get MD5 hash for a character vector

Description

Writesx to a temporary fileusingwriteChar() and computes themd5sum()on that file, removing the file afterwards.

Usage

util_md5sum_str(x)

Arguments

x

character(), vector to compute the MD5 for.

Value

character(1), MD5 hash of a text filecreated fromx usingwriteChar().

Examples

  nhlapi:::util_md5sum_str("test")

Prepare player ids based on player names

Description

Prepare player ids based on player names

Usage

util_prepare_player_ids(playerNames, map = getOption("nhlapi_player_map"))

Arguments

playerNames

character(), vector of one or more player names.Not case sensitive for convenience.

map

data.frame, with 2 columns:

  • nameMd5:character() of hashed player names

  • id:integer() of player ids used by the NHL API

Value

integer(), named vector of found valid playerids, those not found omitted.

Examples

  nhlapi:::util_prepare_player_ids(c("joe sakic", "fake player"))

Description

Removes the element namedel fromx ifpresent and keeps the information as an equally namedattribute.

Usage

util_process_copyright(x, el = "copyright")

Arguments

x

list(), to be processed.

el

character(1), name of the element to remove.Defaults to"copyright" as this is the intended useof the function.

Value

list, with theel element removed and addedas attribute, if it is present inx. Unchangedxotherwise.


Convert time columns from"mm:ss" to numeric minutes

Description

Convert time columns from"mm:ss" to numeric minutes

Usage

util_process_minsonice(df, patt = "timeOn|TimeOn")

Arguments

df

data.frame, data to examine.

patt

character(1), pattern to match column namesthat contain time information in"mm:ss" format.

Value

data.frame, with time columns converted from"mm:ss" characters to numeric minutes.


Safelyrbind multiple data.frames

Description

Attempts to replacedo.call(rbind, lst)taking into consideration that some data frames inlst can have missing columns. Those are filled byNA values.

Usage

util_rbindlist(lst, fill = TRUE)

Arguments

lst

list(), of data frames to berbind-ed into one.

fill

logical(1), ifFALSE, this function justreturnsdo.call(rbind, lst).

Value

data.frame, the elements oflst,rbind-ed into one.

Examples

  nhlapi:::util_rbindlist(list(    datasets::mtcars[1, 2:3],    datasets::mtcars[2, 4:5]  ))

Report errors encountered duringnhl_get_data

Description

Report errors encountered duringnhl_get_data

Usage

util_report_get_data_errors(x, reporter = log_e, ...)

Arguments

x

list, results created bynhl_get_data().

reporter

function, used to report the constructederror message, e.g.message,warning,writeLines,etc.

...

further arguments passed toreporter, e.g.con = file("~/log.txt") in casewriteLines is thereporter.

Value

character(), URLs for which the retrievalresulted in an error, invisibly. Optional side-effects.

Examples

## Not run:   # Write errors to a temporary text file  tmpFile <- tempfile()  util_report_get_data_errors(    nhl_get_data(nhl_url_players(c("none", "8451101", "some"))),    reporter = writeLines,    con = tmpFile  )## End(Not run)

[8]ページ先頭

©2009-2025 Movatter.jp