ST-558-Project-1


Project maintained by yemoray Hosted on GitHub Pages — Theme by mattgraham

Packages required to load and analyse the data

The following packages are needed for reading and analyzing the data:

packages <- c("tidyverse","httr","jsonlite","rmarkdown", "knitr","DT","summarytools")
lapply(packages, library, character.only = TRUE)

Introduction

This vignette reads data from the NHL records API (using functions from the httr and jsonlite packages) and shows some basic exploratory data analysis using tools available in the tidyverse package.

Reading data from the National Hockey League’s (NHL) records API

Franchise data

The franchise data returns id, firstSeasonId and last SeasonId and name of every team in the history of the NHL.

get_franchise_data <- function()  {
  prefix_url <- "https://records.nhl.com/site/api"
  franchise_url <- paste0(prefix_url,"/","franchise")
  franchise_list <- franchise_url %>% 
                    GET() %>% 
                    content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
  return(franchise_list$data)
}

Franchise team totals

The franchise team totals returns the total stats for every franchise:

get_franchise_team_totals <- function()  {
  prefix_url <- "https://records.nhl.com/site/api"
  franchise_totals_url <- paste0(prefix_url,"/","franchise-team-totals")
  franchise_totals_list <- franchise_totals_url %>% 
                            GET() %>%
                            content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
  return(franchise_totals_list$data)
}

Franchise season records

The franchise season records drills down into season records for a specified franchise when the franchiseId, represented as ID below, is provided.As an option, both the ID and full team name can be supplied, as long as they are matched in the database

get_franchise_season_records <- function(ID, name){
  if  (ID %in% c(1:nrow(get_franchise_data())))  {
    if  (missing(name))  {
      prefix_url <- "https://records.nhl.com/site/api"
      franchise_season_records_url <- paste0(prefix_url,"/","franchise-season-records?cayenneExp=franchiseId=",ID)
      franchise_season_records_list <- franchise_season_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
      return(franchise_season_records_list$data)
  
    } else if  (name %in% get_franchise_data()$fullName)  {
        if  (ID != which(get_franchise_data()$fullName == name))  {
          stop ("The franchise id entered is not for the team selected")       #This warns the user if there is a name and ID mismatch.
        }
        ID <- which(get_franchise_data()$fullName == name)
        prefix_url <- "https://records.nhl.com/site/api"
        franchise_season_records_url <- paste0(prefix_url,"/","franchise-season-records?cayenneExp=franchiseId=",ID)
        franchise_season_records_list <- franchise_season_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE) 
    
        return(franchise_season_records_list$data)
      }
  }   
}

For example, the team with franchiseID = 6 (Boston Bruins) has the following season record:

kable(head(get_franchise_season_records(6,"Boston Bruins")))
id fewestGoals fewestGoalsAgainst fewestGoalsAgainstSeasons fewestGoalsSeasons fewestLosses fewestLossesSeasons fewestPoints fewestPointsSeasons fewestTies fewestTiesSeasons fewestWins fewestWinsSeasons franchiseId franchiseName homeLossStreak homeLossStreakDates homePointStreak homePointStreakDates homeWinStreak homeWinStreakDates homeWinlessStreak homeWinlessStreakDates lossStreak lossStreakDates mostGameGoals mostGameGoalsDates mostGoals mostGoalsAgainst mostGoalsAgainstSeasons mostGoalsSeasons mostLosses mostLossesSeasons mostPenaltyMinutes mostPenaltyMinutesSeasons mostPoints mostPointsSeasons mostShutouts mostShutoutsSeasons mostTies mostTiesSeasons mostWins mostWinsSeasons pointStreak pointStreakDates roadLossStreak roadLossStreakDates roadPointStreak roadPointStreakDates roadWinStreak roadWinStreakDates roadWinlessStreak roadWinlessStreakDates winStreak winStreakDates winlessStreak winlessStreakDates
6 147 172 1952-53 (70) 1955-56 (70) 13 1971-72 (78) 38 1961-62 (70) 5 1972-73 (78) 14 1962-63 (70) 6 Boston Bruins 11 Dec 08 1924 - Feb 17 1925 27 Nov 22 1970 - Mar 20 1971 20 Dec 03 1929 - Mar 18 1930 11 Dec 08 1924 - Feb 17 1925 11 Dec 03 1924 - Jan 05 1925 14 Jan 21 1945 - NYR 3 @ BOS 14 399 306 1961-62 (70) 1970-71 (78) 47 1961-62 (70), 1996-97 (82) 2443 1987-88 (80) 121 1970-71 (78) 15 1927-28 (44) 21 1954-55 (70) 57 1970-71 (78) 23 Dec 22 1940 - Feb 23 1941 14 Dec 27 1964 - Feb 21 1965 16 Jan 11 2014 - Mar 30 2014 9 Mar 02 2014 - Mar 30 2014 14 Oct 12 1963 - Dec 14 1963, Dec 27 1964 - Feb 21 1965, Nov 09 1966 - Jan 07 1967 14 Dec 03 1929 - Jan 09 1930 20 Jan 28 1962 - Mar 11 1962

Franchise goalie records

The franchise season records returns goalie records for a specified franchise when the franchiseId with or without the team name is provided:

get_franchise_goalie_records <- function(ID, name){
  if  (ID %in% c(1:nrow(get_franchise_data())))  {
    if  (missing(name))  {
      prefix_url <- "https://records.nhl.com/site/api"
      franchise_goalie_records_url <- paste0(prefix_url,"/","franchise-goalie-records?cayenneExp=franchiseId=",ID)
      franchise_goalie_records_list <- franchise_goalie_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
      return(franchise_goalie_records_list$data)
  
    } else if  (name %in% get_franchise_data()$fullName)  {
        if  (ID != which(get_franchise_data()$fullName == name))  {
          stop ("The franchise id entered is not for the team selected")
        }
        ID <- which(get_franchise_data()$fullName == name)
        prefix_url <- "https://records.nhl.com/site/api"
        franchise_goalie_records_url <- paste0(prefix_url,"/","franchise-goalie-records?cayenneExp=franchiseId=",ID)
        franchise_goalie_records_list <- franchise_goalie_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
        return(franchise_goalie_records_list$data)
      }
  }   
}

Franchise skater records

The franchise team totals returns the skater records.when the franchiseId with or without the team name is provided:

get_franchise_skater_records <- function(ID, name){
  if  (ID %in% c(1:nrow(get_franchise_data())))  {
    if  (missing(name))  {
      prefix_url <- "https://records.nhl.com/site/api"
      franchise_skater_records_url <- paste0(prefix_url,"/","franchise-skater-records?cayenneExp=franchiseId=",ID)
      franchise_skater_records_list <- franchise_skater_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
      return(franchise_skater_records_list$data)
  
    } else if  (name %in% get_franchise_data()$fullName)  {
        if  (ID != which(get_franchise_data()$fullName == name))  {
          stop ("The franchise id entered is not for the team selected")
        }
        ID <- which(get_franchise_data()$fullName == name)
        prefix_url <- "https://records.nhl.com/site/api"
        franchise_skater_records_url <- paste0(prefix_url,"/","franchise-skater-records?cayenneExp=franchiseId=",ID)
        franchise_skater_records_list <- franchise_skater_records_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
        return(franchise_skater_records_list$data)
      }
  }
}

Franchise detail

The franchise detail returns admin history and retired numbers when the mostRecentTeamId, represented as TeamID is provided. As an option, both the TeamID and full team name can be supplied, as long as they are matched in the database:

get_franchise_detail <- function(TeamID, name){
  if  (TeamID %in% c(1:max(get_franchise_data()$mostRecentTeamId)))  {
    if  (missing(name))  {
      prefix_url <- "https://records.nhl.com/site/api"
      get_franchise_detail_url <- paste0(prefix_url,"/","franchise-detail?cayenneExp=mostRecentTeamId=",TeamID)
      get_franchise_detail_list <- get_franchise_detail_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
  
      return(get_franchise_detail_list$data)
  
    } else if  (name %in% get_franchise_data()$fullName)  {
        if  (TeamID != get_franchise_data()$mostRecentTeamId[which(get_franchise_data()$fullName == name)])  {
          stop ("The Team id entered is not for the team selected")
        }
        TeamID <- get_franchise_data()$mostRecentTeamId[which(get_franchise_data()$fullName == name)]
        prefix_url <- "https://records.nhl.com/site/api"
        get_franchise_detail_url <- paste0(prefix_url,"/","franchise-detail?cayenneExp=mostRecentTeamId=",TeamID)
        get_franchise_detail_list <- get_franchise_detail_url %>% GET() %>% content(.,"text") %>% fromJSON(.,flatten = TRUE)
    
        return(get_franchise_detail_list$data)
      }
  }   
}

Reading data from the National Hockey League’s (NHL) stat API

The following code gets the data about individual teams, or all teams from the NHL stats API when the mostRecentTeamId, represented here as TeamID, is provided, or if “all” is used as the argument:

get_team_stat <- function(TeamID){
  if  (TeamID %in% c(1:max(get_franchise_data()$mostRecentTeamId)))  {
    get_single_team_stat_url <- paste0("https://statsapi.web.nhl.com/api/v1/teams/",TeamID,"?expand=team.stats")
    info <-  get_single_team_stat_url %>% 
    GET() %>% content(.,"text") %>% 
    fromJSON(.,flatten = TRUE) %>% 
    as.data.frame() %>% tbl_df() 
    info_full <- unnest(unnest(info,cols = c(teams.teamStats)),cols = c(splits))
    return(info_full)
    
  }  else if (identical(TeamID, "all")){
      get_single_team_stat_url <- "https://statsapi.web.nhl.com/api/v1/teams/?expand=team.stats"
      info <-  get_single_team_stat_url %>% 
      GET() %>% content(.,"text") %>% 
      fromJSON(.,flatten = TRUE) %>% 
      as.data.frame() %>% tbl_df() 
      info_full <- unnest(unnest(info,cols = c(teams.teamStats)),cols = c(splits))
      return(info_full)
    }

}

Wrapper function to access API endpoints

The wrapper function is called `get_NHL_info. The choice of endpoint selections are any of:

The franchise ID must be between 1 and 39, and the team ID must be between 1 and 55 or an error message will be generated.

Please refer to NHL records API for a clear explanation of the purpose of the API endpoints.

get_NHL_info<- function(endpoint,ID){

  if(endpoint == "Franchise data")  {
    get_franchise_data()
  }  else if  (endpoint == "Franchise team totals")  {
      get_franchise_team_totals()
      }  else if  (endpoint == "Franchise season records"){
          get_franchise_season_records(ID) 
          }  else if  (endpoint == "Franchise goalie records"){
              get_franchise_goalie_records (ID)
              }  else if  (endpoint == "Franchise skater records"){
                  get_franchise_skater_records (ID) 
                  }  else if  (endpoint == "Franchise detail"){
                      get_franchise_detail (ID)
                      }

}

Exploratory Data Analysis

Data from 2 endpoints

Some data for active and inactive players of the Dallas Stars

The table below shows some data for active and inactive players for the Dallas Stars, only the first few rows are shown, to conserve space:

skater_records <- get_NHL_info("Franchise skater records",15)
skater_records_subset <- skater_records %>% select(activePlayer,firstName,lastName,gamesPlayed,positionCode,seasons)
kable(head(skater_records_subset,caption = "Summary of active and inactive Dallas Stars Players by position ,games played and number of seasons"))
activePlayer firstName lastName gamesPlayed positionCode seasons
FALSE Chris Ahrens 52 D 5
FALSE Mike Antonovich 14 C 2
FALSE Norm Beaudin 12 R 1
FALSE Don Blackburn 4 L 1
FALSE Chuck Arnason 1 R 1
FALSE John Baby 2 D 1

Home and away records for all teams during regular season

The table below summarize the home and away records for all teams during regular season. Only the first few rows are shown:

team_totals <- get_franchise_team_totals()
kable(head(team_totals %>% 
     filter(gameTypeId==2) %>%
     select(teamName,starts_with("home"),starts_with("road"))))
teamName homeLosses homeOvertimeLosses homeTies homeWins roadLosses roadOvertimeLosses roadTies roadWins
New Jersey Devils 525 85 96 790 686 84 123 604
New York Islanders 678 84 170 963 909 82 177 725
New York Rangers 1143 76 448 1614 1573 77 360 1269
Philadelphia Flyers 584 93 193 1216 868 90 264 863
Pittsburgh Penguins 683 60 205 1138 1051 91 178 765
Boston Bruins 960 92 376 1885 1443 99 415 1356

Creation of new variables

The following table shows home win percentage and road win percentage for all teams during regular season. Only the first few rows are shown:

regular_season_records <- team_totals %>% 
                          filter(gameTypeId==2) %>% 
                          select(teamName,starts_with("home"),starts_with("road"))

regular_season_win_percent <-regular_season_records %>% 
                             mutate(HomeWinPercent=(homeWins/(homeWins+homeTies+homeLosses)),roadWinPercent=(roadWins/(roadWins+roadTies+roadLosses))) %>% 
                             select(teamName,HomeWinPercent,roadWinPercent)

kable(head(regular_season_win_percent, caption = "Home and away win percentages during regular season"),digits = 2)
teamName HomeWinPercent roadWinPercent
New Jersey Devils 0.56 0.43
New York Islanders 0.53 0.40
New York Rangers 0.50 0.40
Philadelphia Flyers 0.61 0.43
Pittsburgh Penguins 0.56 0.38
Boston Bruins 0.59 0.42

The same records for playoffs were also calculated and will be displayed in a graph.

playoff_records <- team_totals %>% 
                  filter(gameTypeId==3) %>% 
                  select(teamName,starts_with("home"),starts_with("road"))

playoff_win_percent <-playoff_records %>% 
                      mutate(HomeWinPercent=(homeWins/(homeWins+homeTies+homeLosses)),roadWinPercent=(roadWins/(roadWins+roadTies+roadLosses))) %>% 
                      select(teamName,HomeWinPercent,roadWinPercent)

kable(head(playoff_win_percent, caption = "Home and away win percentages during playoffs"),digits = 2)

The regular season records and playoff records data frames are merged below prior to graphic representation. Some columns are renamed first, also rows with missing records are removed:

playoff_win_percent_rn <- playoff_win_percent  %>% 
                          rename(HomeWinPercent_po=HomeWinPercent, roadWinPercent_po=roadWinPercent) %>% tbl_df()

regular_season_win_percent_rn <- regular_season_win_percent  %>% 
                                 rename(HomeWinPercent_rs=HomeWinPercent, roadWinPercent_rs=roadWinPercent) %>% tbl_df()

win_percent_join <- full_join(playoff_win_percent_rn,regular_season_win_percent_rn, by = "teamName") %>% drop_na()

Contingency tables

Summary of active and inactive players for the Dallas Stars

The table below summarizes an earlier table, it shows the number of currently active and inactive players for the Dallas Stars:

skater_records$activePlayer <-  as.factor(skater_records$activePlayer)
levels(skater_records$activePlayer)  <-  c("Inactive", "Active")
kable(table(skater_records$activePlayer, skater_records$positionCode),caption = "Summary of Dallas Stars Players by position and activity")
Summary of Dallas Stars Players by position and activity
C D L R
Inactive 137 183 125 115
Active 16 23 9 11

Summary of Dallas Stars Players by position and activity

Table comparing number of shut outs with time spent in the penalty box

The code below categorizes shut outs and penalty minutes

#categorizing shutouts
team_totals <- mutate(team_totals, shut_out_format = 
                  ifelse(shutouts %in% 0:50, "Not defensive",
                  ifelse(shutouts %in% 51:100, "Slightly defensive",
                  ifelse(shutouts %in% 101:150, "Defensive", 
                  ifelse(shutouts >150, "Very defensive", "")))))
team_totals$shut_out_format <- factor(team_totals$shut_out_format, levels=c("Not defensive", "Slightly defensive", "Defensive","Very defensive"))

#categorizing penalty minutes
team_totals <- mutate(team_totals, penalty_mins_format = 
                  ifelse(penaltyMinutes %in% 0:25000, "Not aggressive",
                  ifelse(penaltyMinutes %in% 25001:50000, "Slightly aggressive",
                  ifelse(penaltyMinutes %in% 50001:75000, "Aggressive",
                  ifelse(penaltyMinutes >75000, "Very aggressive", "")))))
team_totals$penalty_mins_format <- factor(team_totals$penalty_mins_format, levels=c("Not aggressive","Slightly aggressive", "Aggressive","Very aggressive"))

shutouts_penaltyminutes_table <- table(team_totals$shut_out_format, team_totals$penalty_mins_format )
kable(shutouts_penaltyminutes_table, caption="Table of Total Number of Shut Outs vs. Total Penalty Minutes")
Table of Total Number of Shut Outs vs. Total Penalty Minutes
Not aggressive Slightly aggressive Aggressive Very aggressive
Not defensive 67 3 0 0
Slightly defensive 6 1 0 0
Defensive 4 6 2 0
Very defensive 0 2 7 7

Table of Total Number of Shut Outs vs. Total Penalty Minutes

It appears being aggressive leads to defensive solidity.

Numerical Summaries

Summary of assists by position for the Dallas Stars

The table below shows that, not, surprisingly, the centers provided the most assists on average.

assist_record  <-  skater_records %>% group_by(positionCode) %>%select(assists) %>% descr(.,stats = "common")
print(assist_record, caption = "Numeric Summaries of Dallas Stars assists by Position")

## Descriptive Statistics  
## assists by positionCode  
## Data Frame: skater_records  
## N: 153  
## 
##                   positionCode = C   positionCode = D   positionCode = L   positionCode = R
## --------------- ------------------ ------------------ ------------------ ------------------
##            Mean              46.70              28.49              31.93              30.56
##         Std.Dev             100.59              59.43              66.01              52.39
##             Min               0.00               0.00               0.00               0.00
##          Median              10.00               6.00               8.00               8.50
##             Max             802.00             438.00             412.00             319.00
##         N.Valid             153.00             206.00             134.00             126.00
##       Pct.Valid             100.00             100.00             100.00             100.00
## 
## Table: Numeric Summaries of Dallas Stars assists by Position

Summary of penalty minutes by position for the Dallas Stars

The table below shows that the centers spend the least time in the penalty box on average.

penalty_record  <-  skater_records %>% group_by(positionCode) %>%select(penaltyMinutes) %>% descr(.,stats = "common")
print(penalty_record, caption = "Numeric Summaries of Dallas Stars penalty minutes by Position")

## Descriptive Statistics  
## penaltyMinutes by positionCode  
## Data Frame: skater_records  
## N: 153  
## 
##                   positionCode = C   positionCode = D   positionCode = L   positionCode = R
## --------------- ------------------ ------------------ ------------------ ------------------
##            Mean              82.31             117.98              92.02             106.29
##         Std.Dev             162.21             212.96             201.62             232.65
##             Min               0.00               0.00               0.00               0.00
##          Median              23.00              34.00              35.50              21.50
##             Max            1170.00            1380.00            1567.00            1883.00
##         N.Valid             153.00             206.00             134.00             126.00
##       Pct.Valid             100.00             100.00             100.00             100.00
## 
## Table: Numeric Summaries of Dallas Stars penalty minutes by Position

Graphics

Graph of regular season home win percent vs playoff home win percent

It appears that, overall, teams that perform well at home during the regular season do as well during the playoffs.

ggplot(data=win_percent_join, aes(y=HomeWinPercent_rs, x=HomeWinPercent_po))+
  geom_point(color="green")+
  geom_abline(slope=1, intercept = 0, color="blue")+
  labs(x="Playoff Home Wins", y="Regular Season Home Wins", title="Scatter of Regular Season vs Playoffs Home Wins")

The boxplot below is a visual representation of the numerical summaries table for penalty minutes shown earlier. This also shows that,unsurprisingly, centers spend the least time in the penalty box.

skater_records$avgPenaltyMinutes = skater_records$penaltyMinutes / skater_records$gamesPlayed

ggplot(data=skater_records%>%filter(gameTypeId==2), aes(x=positionCode, y=avgPenaltyMinutes))+
  geom_boxplot(aes(fill=positionCode))+
  geom_jitter()+
  labs(x="Position", y="Average Penalty Minutes Per Game", fill="Position", title = "Boxplot of Average Penalty Minutes by Position for the Dallas Stars")

The bar plot below show the goals scored by position by the Dallas Stars team. The centers clearly score the most goals for the Dallas Stars.

ggplot(data=skater_records, aes(x=positionCode, y=points))+
  geom_bar(stat = "identity", aes(fill=positionCode))+
  labs(x="Position", y="Points", fill="Position", title="Points scored by position for the Dallas Stars")

The bar plot below shows that teams that are very aggressive, also tend to have very good defensive solidity.

ggplot(data=team_totals, aes(x=team_totals$penalty_mins_format))+
  geom_bar(aes(fill=as.factor(team_totals$shut_out_format)))+ 
  labs(x="Team Aggression", title="Points scored by position for the Dallas Stars")+ 
  scale_fill_discrete(name="Defensive Solidity", labels=c("Not defensive", "Slightly defensive", "Defensive","Very defensive")) + 
  coord_flip()

The home win percent vs road win percent shown in an earlier table are visualized in the scatterplot below. It seems home advantage counts for little..

ggplot(data=regular_season_win_percent, aes(y=HomeWinPercent, x=roadWinPercent))+
  geom_point(color="red")+ geom_smooth(method = "lm")+ 
  geom_abline(slope=1, intercept = 0, color="green")+
  labs(x="Road Wins %", y="Home Wins %", title="Scatterplot of Away vs Home Wins Percentages")

The histogram below shows the distribution of seasons spent by position for the Dallas Stars.The majority of players spent less than 5 seasons, but it seems defenders tend to spend longer at the Dallas Stars.

ggplot(data=skater_records, aes(x=seasons, y=..density..))+
  geom_histogram(aes(fill=activePlayer), position = "dodge")+
  facet_wrap(~positionCode)+
  labs(x="Seasons", y="Count", title = "Distribution of seasons by Position for the Dallas Stars", fill="Active Player")