I need your help!

I want your feedback to make the book better for you and other readers. If you find typos, errors, or places where the text may be improved, please let me know. The best ways to provide feedback are by GitHub or hypothes.is annotations.

Opening an issue or submitting a pull request on GitHub: https://github.com/isaactpetersen/Fantasy-Football-Analytics-Textbook

Hypothesis Adding an annotation using hypothes.is. To add an annotation, select some text and then click the symbol on the pop-up menu. To see the annotations of others, click the symbol in the upper right-hand corner of the page.

3  Getting Started with R for Data Analysis

The book uses R for statistical analyses (http://www.r-project.org). R is a free software environment; you can download it at no charge here: https://cran.r-project.org.

3.1 Initial Setup

To get started, follow the following steps:

  1. Install R: https://cran.r-project.org
  2. Install RStudio Desktop: https://posit.co/download/rstudio-desktop
  3. After installing RStudio, open RStudio and run the following code in the console to install several key R packages:
Code
install.packages(
  c("petersenlab","ffanalytics","nflreadr","nflfastR","nfl4th","nflplotR",
  "gsisdecoder","progressr","lubridate","tidyverse","psych"))
Note 3.1: If you are in Dr. Petersen’s class

If you are in Dr. Petersen’s class, also perform the following steps:

  1. Set up a free account on GitHub.com.
  2. Download GitHub Desktop: https://desktop.github.com

3.2 Installing Packages

You can install R packages using the following syntax:

Code
install.packages("INSERT_PACKAGE_NAME_HERE")

For instance, you can use the following code to install the nflreadr package:

Code
install.packages("nflreadr")

3.3 Load Packages

Code
library("ffanalytics")
library("nflreadr")
library("nflfastR")
library("nfl4th")
library("nflplotR")
library("progressr")
library("lubridate")
library("tidyverse")

3.4 Download Football Data

3.4.1 Players

Code
nfl_players <- progressr::with_progress(
  nflreadr::load_players())

3.4.2 Teams

Code
nfl_teams <- progressr::with_progress(
  nflreadr::load_teams(current = TRUE))

3.4.3 Player Info

3.4.4 Rosters

A Data Dictionary for rosters is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_rosters.html

Code
nfl_rosters <- progressr::with_progress(
  nflreadr::load_rosters(seasons = TRUE))

nfl_rosters_weekly <- progressr::with_progress(
  nflreadr::load_rosters_weekly(seasons = TRUE))

3.4.5 Game Schedules

A Data Dictionary for game schedules data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_schedules.html

Code
nfl_schedules <- progressr::with_progress(
  nflreadr::load_schedules(seasons = TRUE))

3.4.6 The Combine

A Data Dictionary for data from the combine is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_combine.html

Code
nfl_combine <- progressr::with_progress(
  nflreadr::load_combine(seasons = TRUE))

3.4.7 Draft Picks

A Data Dictionary for draft picks data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_draft_picks.html

Code
nfl_draftPicks <- progressr::with_progress(
  nflreadr::load_draft_picks(seasons = TRUE))

3.4.8 Depth Charts

A Data Dictionary for data from weekly depth charts is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_depth_charts.html

Code
nfl_depthCharts <- progressr::with_progress(
  nflreadr::load_depth_charts(seasons = TRUE))

3.4.9 Play-By-Play Data

To download play-by-play data from prior weeks and seasons, we can use the load_pbp() function of the nflreadr package. We add a progress bar using the with_progress() function from the progressr package because it takes a while to run. A Data Dictionary for the play-by-play data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_pbp.html

Note 3.2: Downloading play-by-play data

Note: the following code takes a while to run.

Code
nfl_pbp <- progressr::with_progress(
  nflreadr::load_pbp(seasons = TRUE))

3.4.10 4th Down Data

Code
nfl_4thdown <- nfl4th::load_4th_pbp(seasons = 2014:2023)

3.4.11 Participation

A Data Dictionary for the participation data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_participation.html

Code
nfl_participation <- progressr::with_progress(
  nflreadr::load_participation(
    seasons = TRUE,
    include_pbp = TRUE))

3.4.12 Historical Weekly Actual Player Statistics

We can download historical week-by-week actual player statistics using the load_player_stats() function from the nflreadr package. A Data Dictionary for statistics for offensive players is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_player_stats.html. A Data Dictionary for statistics for defensive players is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_player_stats_def.html.

Code
nfl_actualStats_offense_weekly <- progressr::with_progress(
  nflreadr::load_player_stats(
    seasons = TRUE,
    stat_type = "offense"))

nfl_actualStats_defense_weekly <- progressr::with_progress(
  nflreadr::load_player_stats(
    seasons = TRUE,
    stat_type = "defense"))

nfl_actualStats_kicking_weekly <- progressr::with_progress(
  nflreadr::load_player_stats(
    seasons = TRUE,
    stat_type = "kicking"))

3.4.13 Injuries

A Data Dictionary for injury data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_injuries.html

Code
nfl_injuries <- progressr::with_progress(
  nflreadr::load_injuries(seasons = TRUE))

3.4.14 Snap Counts

A Data Dictionary for snap counts data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_snap_counts.html

Code
nfl_snapCounts <- progressr::with_progress(
  nflreadr::load_snap_counts(seasons = TRUE))

3.4.15 ESPN QBR

A Data Dictionary for ESPN QBR data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_espn_qbr.html

Code
nfl_espnQBR_seasonal <- progressr::with_progress(
  nflreadr::load_espn_qbr(
    seasons = TRUE,
    summary_type = c("season")))

nfl_espnQBR_weekly <- progressr::with_progress(
  nflreadr::load_espn_qbr(
    seasons = TRUE,
    summary_type = c("weekly")))

nfl_espnQBR_weekly$game_week <- as.character(nfl_espnQBR_weekly$game_week)

nfl_espnQBR <- bind_rows(
  nfl_espnQBR_seasonal,
  nfl_espnQBR_weekly
)

3.4.16 NFL Next Gen Stats

A Data Dictionary for NFL Next Gen Stats data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_nextgen_stats.html

Code
nfl_nextGenStats_pass_weekly <- progressr::with_progress(
  nflreadr::load_nextgen_stats(
    seasons = TRUE,
    stat_type = c("passing")))

nfl_nextGenStats_rush_weekly <- progressr::with_progress(
  nflreadr::load_nextgen_stats(
    seasons = TRUE,
    stat_type = c("rushing")))

nfl_nextGenStats_rec_weekly <- progressr::with_progress(
  nflreadr::load_nextgen_stats(
    seasons = TRUE,
    stat_type = c("receiving")))

nfl_nextGenStats_weekly <- bind_rows(
  nfl_nextGenStats_pass_weekly,
  nfl_nextGenStats_rush_weekly,
  nfl_nextGenStats_rec_weekly
)

3.4.17 Advanced Stats from PFR

A Data Dictionary for PFR passing data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_pfr_passing.html

Code
nfl_advancedStatsPFR_pass_seasonal <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("pass"),
    summary_level = c("season")))

nfl_advancedStatsPFR_pass_weekly <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("pass"),
    summary_level = c("week")))

nfl_advancedStatsPFR_rush_seasonal <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("rush"),
    summary_level = c("season")))

nfl_advancedStatsPFR_rush_weekly <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("rush"),
    summary_level = c("week")))

nfl_advancedStatsPFR_rec_seasonal <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("rec"),
    summary_level = c("season")))

nfl_advancedStatsPFR_rec_weekly <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("rec"),
    summary_level = c("week")))

nfl_advancedStatsPFR_def_seasonal <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("def"),
    summary_level = c("season")))

nfl_advancedStatsPFR_def_weekly <- progressr::with_progress(
  nflreadr::load_pfr_advstats(
    seasons = TRUE,
    stat_type = c("def"),
    summary_level = c("week")))

nfl_advancedStatsPFR <- bind_rows(
  nfl_advancedStatsPFR_pass_seasonal,
  nfl_advancedStatsPFR_pass_weekly,
  nfl_advancedStatsPFR_rush_seasonal,
  nfl_advancedStatsPFR_rush_weekly,
  nfl_advancedStatsPFR_rec_seasonal,
  nfl_advancedStatsPFR_rec_weekly,
  nfl_advancedStatsPFR_def_seasonal,
  nfl_advancedStatsPFR_def_weekly,
)

3.4.18 Player Contracts

A Data Dictionary for player contracts data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_contracts.html

Code
nfl_playerContracts <- progressr::with_progress(
  nflreadr::load_contracts())

3.4.19 FTN Charting Data

A Data Dictionary for FTN Charting data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_ftn_charting.html

Code
nfl_ftnCharting <- progressr::with_progress(
  nflreadr::load_ftn_charting(seasons = TRUE))

3.4.20 Fantasy Player IDs

A Data Dictionary for fantasy player ID data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_ff_playerids.html

Code
nfl_playerIDs <- progressr::with_progress(
  nflreadr::load_ff_playerids())

3.4.21 FantasyPros Rankings

A Data Dictionary for FantasyPros ranking data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_ff_rankings.html

Code
#nfl_rankings <- progressr::with_progress( # currently throws error
#  nflreadr::load_ff_rankings(type = "all"))

nfl_rankings_draft <- progressr::with_progress(
  nflreadr::load_ff_rankings(type = "draft"))

nfl_rankings_weekly <- progressr::with_progress(
  nflreadr::load_ff_rankings(type = "week"))

nfl_rankings <- bind_rows(
  nfl_rankings_draft,
  nfl_rankings_weekly
)

3.4.22 Expected Fantasy Points

A Data Dictionary for expected fantasy points data is located at the following link: https://nflreadr.nflverse.com/articles/dictionary_ff_opportunity.html

Code
nfl_expectedFantasyPoints_weekly <- progressr::with_progress(
  nflreadr::load_ff_opportunity(
    seasons = TRUE,
    stat_type = "weekly",
    model_version = "latest"
  ))

nfl_expectedFantasyPoints_pass <- progressr::with_progress(
  nflreadr::load_ff_opportunity(
    seasons = TRUE,
    stat_type = "pbp_pass",
    model_version = "latest"
  ))

nfl_expectedFantasyPoints_rush <- progressr::with_progress(
  nflreadr::load_ff_opportunity(
    seasons = TRUE,
    stat_type = "pbp_rush",
    model_version = "latest"
  ))

nfl_expectedFantasyPoints_weekly$season <- as.integer(nfl_expectedFantasyPoints_weekly$season)

nfl_expectedFantasyPoints_offense <- bind_rows(
  nfl_expectedFantasyPoints_pass,
  nfl_expectedFantasyPoints_rush
)

3.5 Data Dictionary

Data Dictionaries are metadata that describe the meaning of the variables in a datset. You can find Data Dictionaries for the various NFL datasets at the following link: https://nflreadr.nflverse.com/articles/index.html.

3.6 Create a Data Frame

Here is an example of creating a data frame:

Code
players <- data.frame(
  ID = 1:12,
  name = c(
    "Ken Cussion",
    "Ben Sacked",
    "Chuck Downfield",
    "Ron Ingback",
    "Rhonda Ball",
    "Hugo Long",
    "Lionel Scrimmage",
    "Drew Blood",
    "Chase Emdown",
    "Justin Time",
    "Spike D'Ball",
    "Isac Ulooz"),
  position = c("QB","QB","QB","RB","RB","WR","WR","WR","WR","TE","TE","LB"),
  age = c(40, 30, 24, 20, 18, 23, 27, 32, 26, 23, NA, 37)
  )

fantasyPoints <- data.frame(
  ID = c(2, 7, 13, 14),
  fantasyPoints = c(250, 170, 65, 15)
)

3.7 Variable Names

To see the names of variables in a data frame, use the following syntax:

Code
names(nfl_players)
 [1] "status"                   "display_name"            
 [3] "first_name"               "last_name"               
 [5] "esb_id"                   "gsis_id"                 
 [7] "suffix"                   "birth_date"              
 [9] "college_name"             "position_group"          
[11] "position"                 "jersey_number"           
[13] "height"                   "weight"                  
[15] "years_of_experience"      "team_abbr"               
[17] "team_seq"                 "current_team_id"         
[19] "football_name"            "entry_year"              
[21] "rookie_year"              "draft_club"              
[23] "college_conference"       "status_description_abbr" 
[25] "status_short_description" "gsis_it_id"              
[27] "short_name"               "smart_id"                
[29] "headshot"                 "draft_number"            
[31] "uniform_number"           "draft_round"             
[33] "season"                  
Code
names(players)
[1] "ID"       "name"     "position" "age"     
Code
names(fantasyPoints)
[1] "ID"            "fantasyPoints"

3.8 Logical Operators

3.8.1 Is Equal To: ==

Code
players$position == "RB"
 [1] FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

3.8.2 Is Not Equal To: !=

Code
players$position != "RB"
 [1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

3.8.3 Is Greater Than: >

Code
players$age > 30
 [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE    NA  TRUE

3.8.4 Is Less Than: <

Code
players$age < 30
 [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE    NA FALSE

3.8.5 Is Greater Than or Equal To: >=

Code
players$age >= 30
 [1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE    NA  TRUE

3.8.6 Is Less Than or Equal To: <=

Code
players$age <= 30
 [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE    NA FALSE

3.8.7 Is In a Value of Another Vector: %in%

Code
players$position %in% c("RB","WR")
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

3.8.8 Is Not In a Value of Another Vector: !(%in%)

Code
!(players$position %in% c("RB","WR"))
 [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

3.8.9 Is Missing: is.na()

Code
is.na(players$age)
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE

3.8.10 Is Not Missing: !is.na()

Code
!is.na(players$age)
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE

3.8.11 And: &

Code
players$position == "WR" & players$age > 26
 [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE

3.8.12 Or: |

Code
players$position == "WR" | players$age > 23
 [1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE    NA  TRUE

3.9 Subset

To subset a data frame, use brackets to specify the subset of rows and columns to keep, where the value/vector before the comma specifies the rows to keep, and the value/vector after the comma specifies the columns to keep:

Code
dataframe[rowsToKeep, columnsToKeep]

You can subset by using any of the following:

  • numeric indices of the rows/columns to keep (or drop)
  • names of the rows/columns to keep (or drop)
  • values of TRUE and FALSE corresponding to which rows/columns to keep

3.9.1 One Variable

To subset one variable, use the following syntax:

Code
players$name
 [1] "Ken Cussion"      "Ben Sacked"       "Chuck Downfield"  "Ron Ingback"     
 [5] "Rhonda Ball"      "Hugo Long"        "Lionel Scrimmage" "Drew Blood"      
 [9] "Chase Emdown"     "Justin Time"      "Spike D'Ball"     "Isac Ulooz"      

or:

Code
players[,"name"]
 [1] "Ken Cussion"      "Ben Sacked"       "Chuck Downfield"  "Ron Ingback"     
 [5] "Rhonda Ball"      "Hugo Long"        "Lionel Scrimmage" "Drew Blood"      
 [9] "Chase Emdown"     "Justin Time"      "Spike D'Ball"     "Isac Ulooz"      

3.9.2 Particular Rows of One Variable

To subset one variable, use the following syntax:

Code
players$name[which(players$position == "RB")]
[1] "Ron Ingback" "Rhonda Ball"

or:

Code
players[which(players$position == "RB"), "name"]
[1] "Ron Ingback" "Rhonda Ball"

3.9.3 Particular Columns (Variables)

To subset particular columns/variables, use the following syntax:

3.9.3.1 Base R

Code
subsetVars <- c("name","age")

players[,c(2,4)]
Code
players[,c("name","age")]
Code
players[,subsetVars]

Or, to drop columns:

Code
dropVars <- c("name","age")

players[,-c(2,4)]
Code
players[,!(names(players) %in% c("name","age"))]
Code
players[,!(names(players) %in% dropVars)]

3.9.3.2 Tidyverse

Code
players %>%
  select(name, age)
Code
players %>%
  select(name:age)
Code
players %>%
  select(all_of(subsetVars))

Or, to drop columns:

Code
players %>%
  select(-name, -age)
Code
players %>%
  select(-c(name:age))
Code
players %>%
  select(-all_of(dropVars))

3.9.4 Particular Rows

To subset particular rows, use the following syntax:

3.9.4.1 Base R

Code
subsetRows <- c(4,5)

players[c(4,5),]
Code
players[subsetRows,]
Code
players[which(players$position == "RB"),]

3.9.4.2 Tidyverse

Code
players %>%
  filter(position == "WR")
Code
players %>%
  filter(position == "WR", age <= 26)
Code
players %>%
  filter(position == "WR" | age >= 26)

3.9.5 Particular Rows and Columns

To subset particular rows and columns, use the following syntax:

3.9.5.1 Base R

Code
players[c(4,5), c(2,4)]
Code
players[subsetRows, subsetVars]
Code
players[which(players$position == "RB"), subsetVars]

3.9.5.2 Tidyverse

Code
players %>%
  filter(position == "RB") %>%
  select(all_of(subsetVars))

3.10 View Data

3.10.1 All Data

To view data, use the following syntax:

Code
View(players)

3.10.2 First 6 Rows/Elements

To view only the first six rows (if a data frame) or elements (if a vector), use the following syntax:

Code
head(nfl_players)
Code
head(nfl_players$display_name)
[1] "'Omar Ellison"    "A'Shawn Robinson" "A.J. Arcuri"      "A.J. Bouye"      
[5] "A.J. Brown"       "A.J. Cann"       

3.11 Data Characteristics

3.11.1 Data Structure

Code
str(nfl_players)
nflvrs_d [20,039 × 33] (S3: nflverse_data/tbl_df/tbl/data.table/data.frame)
 $ status                  : chr [1:20039] "RET" "ACT" "ACT" "RES" ...
 $ display_name            : chr [1:20039] "'Omar Ellison" "A'Shawn Robinson" "A.J. Arcuri" "A.J. Bouye" ...
 $ first_name              : chr [1:20039] "'Omar" "A'Shawn" "A.J." "Arlandus" ...
 $ last_name               : chr [1:20039] "Ellison" "Robinson" "Arcuri" "Bouye" ...
 $ esb_id                  : chr [1:20039] "ELL711319" "ROB367960" "ARC716900" "BOU651714" ...
 $ gsis_id                 : chr [1:20039] "00-0004866" "00-0032889" "00-0037845" "00-0030228" ...
 $ suffix                  : chr [1:20039] NA NA NA NA ...
 $ birth_date              : chr [1:20039] NA "1995-03-21" NA "1991-08-16" ...
 $ college_name            : chr [1:20039] NA "Alabama" "Michigan State" "Central Florida" ...
 $ position_group          : chr [1:20039] "WR" "DL" "OL" "DB" ...
 $ position                : chr [1:20039] "WR" "DT" "T" "CB" ...
 $ jersey_number           : int [1:20039] 84 91 61 24 11 60 6 81 63 20 ...
 $ height                  : num [1:20039] 73 76 79 72 72 75 76 69 76 72 ...
 $ weight                  : int [1:20039] 200 330 320 191 226 325 220 190 280 183 ...
 $ years_of_experience     : chr [1:20039] "2" "8" "2" "8" ...
 $ team_abbr               : chr [1:20039] "LAC" "NYG" "LA" "CAR" ...
 $ team_seq                : int [1:20039] NA 1 NA 1 1 1 1 NA NA NA ...
 $ current_team_id         : chr [1:20039] "4400" "3410" "2510" "0750" ...
 $ football_name           : chr [1:20039] NA "A'Shawn" "A.J." "A.J." ...
 $ entry_year              : int [1:20039] NA 2016 2022 2013 2019 2015 2019 NA NA NA ...
 $ rookie_year             : int [1:20039] NA 2016 2022 2013 2019 2015 2019 NA NA NA ...
 $ draft_club              : chr [1:20039] NA "DET" "LA" NA ...
 $ college_conference      : chr [1:20039] NA "Southeastern Conference" "Big Ten Conference" "American Athletic Conference" ...
 $ status_description_abbr : chr [1:20039] NA "A01" "A01" "R01" ...
 $ status_short_description: chr [1:20039] NA "Active" "Active" "R/Injured" ...
 $ gsis_it_id              : int [1:20039] NA 43335 54726 40688 47834 42410 48335 NA NA NA ...
 $ short_name              : chr [1:20039] NA "A.Robinson" "A.Arcuri" "A.Bouye" ...
 $ smart_id                : chr [1:20039] "3200454c-4c71-1319-728e-d49d3d236f8f" "3200524f-4236-7960-bf20-bc060ac0f49c" "32004152-4371-6900-5185-8cdd66b2ad11" "3200424f-5565-1714-cb38-07c822111a12" ...
 $ headshot                : chr [1:20039] NA "https://static.www.nfl.com/image/private/f_auto,q_auto/league/qgiwxchd1lmgszfunys8" NA "https://static.www.nfl.com/image/private/f_auto,q_auto/league/cpgi2hbhnmvs1oczkzas" ...
 $ draft_number            : int [1:20039] NA 46 261 NA 51 67 NA NA NA NA ...
 $ uniform_number          : chr [1:20039] NA "91" "61" "24" ...
 $ draft_round             : chr [1:20039] NA NA NA NA ...
 $ season                  : int [1:20039] NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, "nflverse_type")= chr "players"
 - attr(*, "nflverse_timestamp")= POSIXct[1:1], format: "2024-03-01 01:18:40"

3.11.2 Data Dimensions

Number of rows and columns:

Code
dim(nfl_players)
[1] 20039    33

3.11.3 Number of Elements

Code
length(nfl_players$display_name)
[1] 20039

3.11.4 Number of Missing Elements

Code
length(nfl_players$college_name[which(is.na(nfl_players$college_name))])
[1] 12127

3.11.5 Number of Non-Missing Elements

Code
length(nfl_players$college_name[which(!is.na(nfl_players$college_name))])
[1] 7912
Code
length(na.omit(nfl_players$college_name))
[1] 7912

3.12 Create New Variables

To create a new variable, use the following syntax:

Code
players$newVar <- NA

Here is an example of creating a new variable:

Code
players$newVar <- 1:nrow(players)

3.13 Recode Variables

Here is an example of recoding a variable:

Code
players$oldVar1 <- NA
players$oldVar1[which(players$position == "QB")] <- "quarterback"
players$oldVar1[which(players$position == "RB")] <- "running back"
players$oldVar1[which(players$position == "WR")] <- "wide receiver"
players$oldVar1[which(players$position == "TE")] <- "tight end"

players$oldVar2 <- NA
players$oldVar2[which(players$age < 30)] <- "young"
players$oldVar2[which(players$age >= 30)] <- "old"

Recode multiple variables:

Code
players %>%
  mutate(across(c(
    oldVar1:oldVar2),
    ~ case_match(
      .,
      c("quarterback","old","running back") ~ 0,
      c("wide receiver","tight end","young") ~ 1)))

3.14 Rename Variables

Code
players <- players %>% 
  rename(
    newVar1 = oldVar1,
    newVar2 = oldVar2)

Using a vector of variable names:

Code
varNamesFrom <- c("oldVar1","oldVar2")
varNamesTo <- c("newVar1","newVar2")

players <- players %>% 
  rename_with(~ varNamesTo, all_of(varNamesFrom))

3.15 Convert the Types of Variables

One variable:

Code
players$factorVar <- factor(players$ID)
players$numericVar <- as.numeric(players$age)
players$integerVar <- as.integer(players$newVar1)
players$characterVar <- as.character(players$newVar2)

Multiple variables:

Code
players %>%
  mutate(across(c(
    ID,
    age),
    as.numeric))
Code
players %>%
  mutate(across(
    age:newVar1,
    as.character))
Code
players %>%
  mutate(across(where(is.factor), as.character))

3.16 Merging/Joins

3.16.1 Overview

Merging (also called joining) merges two data objects using a shared set of variables called “keys.” The keys are the variable(s) that uniquely identify each row (i.e., they account for the levels of nesting). In some data objects, the key might be the player’s identification number (e.g., player_id). However, some data objects have multiple keys. For instance, in long form data objects, each participant may have multiple rows corresponding to multiple seasons. In this case, the keys may be player_id and season. If a participant has multiple rows corresponding to seasons and games/weeks, the keys are player_id, season, and week. In general, each row should have a value on each of the keys; there should be no missingness in the keys.

To merge two objects, the key(s) that will be used to match the records must be present in both objects. The keys are used to merge the variables in object 1 (x) with the variables in object 2 (y). Different merge types select different rows to merge.

Note: if the two objects include variables with the same name (apart from the keys), R will not know how you want each to appear in the merged object. So, it will add a suffix (e.g., .x, .y) to each common variable to indicate which object (i.e., object x or object y) the variable came from, where object x is the first object—i.e., the object to which object y (the second object) is merged. In general, apart from the keys, you should not include variables with the same name in two objects to be merged. To prevent this, either remove or rename the shared variable in one of the objects, or include the shared variable as a key. However, as described above, you should include it as a key only if it uniquely identifies each row in terms of levels of nesting.

3.16.2 Data Before Merging

Here are the data in the players object:

Code
players
Code
dim(players)
[1] 12 10

The data are structured in ID form. That is, every row in the dataset is uniquely identified by the variable, ID.

Here are the data in the fantasyPoints object:

Code
fantasyPoints
Code
dim(fantasyPoints)
[1] 4 2

3.16.3 Types of Joins

3.16.3.1 Visual Overview of Join Types

Below is a visual that depicts various types of merges/joins. Object x is the circle labeled as x. Object y is the circle labeled as y. The area of overlap in the Venn diagram indicates the rows on the keys that are shared between the two objects (e.g., the same player_id, season, and week). The non-overlapping area indicates the rows on the keys that are unique to each object. The shaded blue area indicates which rows (on the keys) are kept in the merged object from each of the two objects, when using each of the merge types. For instance, a left outer join keeps the shared rows and the rows that are unique to object x, but it drops the rows that are unique to object y.

Types of merges/joins

3.16.3.2 Full Outer Join

A full outer join includes all rows in \(x\) or \(y\). It returns columns from \(x\) and \(y\). Here is how to merge two data frames using a full outer join (i.e., “full join”):

Code
fullJoinData <- full_join(
  players,
  fantasyPoints,
  by = "ID")

fullJoinData
Code
dim(fullJoinData)
[1] 14 11

3.16.3.3 Left Outer Join

A left outer join includes all rows in \(x\). It returns columns from \(x\) and \(y\). Here is how to merge two data frames using a left outer join (“left join”):

Code
leftJoinData <- left_join(
  players,
  fantasyPoints,
  by = "ID")

leftJoinData
Code
dim(leftJoinData)
[1] 12 11

3.16.3.4 Right Outer Join

A right outer join includes all rows in \(y\). It returns columns from \(x\) and \(y\). Here is how to merge two data frames using a right outer join (“right join”):

Code
rightJoinData <- right_join(
  players,
  fantasyPoints,
  by = "ID")

rightJoinData
Code
dim(rightJoinData)
[1]  4 11

3.16.3.5 Inner Join

An inner join includes all rows that are in both \(x\) and \(y\). An inner join will return one row of \(x\) for each matching row of \(y\), and can duplicate values of records on either side (left or right) if \(x\) and \(y\) have more than one matching record. It returns columns from \(x\) and \(y\). Here is how to merge two data frames using an inner join:

Code
innerJoinData <- inner_join(
  players,
  fantasyPoints,
  by = "ID")

innerJoinData
Code
dim(innerJoinData)
[1]  2 11

3.16.3.6 Semi Join

A semi join is a filter. A left semi join returns all rows from \(x\) with a match in \(y\). That is, it filters out records from \(x\) that are not in \(y\). Unlike an inner join, a left semi join will never duplicate rows of \(x\), and it includes columns from only \(x\) (not from \(y\)). Here is how to merge two data frames using a left semi join:

Code
semiJoinData <- semi_join(
  players,
  fantasyPoints,
  by = "ID")

semiJoinData
Code
dim(semiJoinData)
[1]  2 10

3.16.3.7 Anti Join

An anti join is a filter. A left anti join returns all rows from \(x\) without a match in \(y\). That is, it filters out records from \(x\) that are in \(y\). It returns columns from only \(x\) (not from \(y\)). Here is how to merge two data frames using a left anti join:

Code
antiJoinData <- anti_join(
  players,
  fantasyPoints,
  by = "ID")

antiJoinData
Code
dim(antiJoinData)
[1] 10 10

3.16.3.8 Cross Join

A cross join combines each row in \(x\) with each row in \(y\).

Code
crossJoinData <- cross_join(
  players,
  fantasyPoints)

crossJoinData
Code
dim(crossJoinData)
[1] 48 12

3.17 Transform Data from Long to Wide

Depending on the analysis, it may be important to restructure the data to be in long or wide form. When the data are in wide form, each player has only one row. When the data are in long form, each player has multiple rows—e.g., a row for each game. The data structure is called wide or long form because a dataset in wide form has more columns and fewer rows (i.e., it appears wider and shorter), whereas a dataset in long form has more rows and fewer columns (i.e., it appears narrower and taller).

Here are the data in the nfl_actualStats_offense_weekly object. The data are structured in “player-season-week form”. That is, every row in the dataset is uniquely identified by the variables, player_id, season, and week. This is an example of long form, because each player has multiple rows.

Original data:

Code
dataLong <- nfl_actualStats_offense_weekly %>% 
  select(player_id, player_display_name, season, week, fantasy_points)

dim(dataLong)
[1] 129739      5
Code
names(dataLong)
[1] "player_id"           "player_display_name" "season"             
[4] "week"                "fantasy_points"     

Below, we widen the data by two variables (season and week), using tidyverse, so that the data are now in “player form” (where each row is uniquely identified by the player_id variable):

Code
dataWide <- dataLong %>% 
  pivot_wider(
    names_from = c(season, week),
    names_glue = "{.value}_{season}_week{week}",
    values_from = fantasy_points)

dim(dataWide)
[1] 4021  530
Code
names(dataWide)
  [1] "player_id"                  "player_display_name"       
  [3] "fantasy_points_1999_week1"  "fantasy_points_1999_week2" 
  [5] "fantasy_points_1999_week4"  "fantasy_points_1999_week7" 
  [7] "fantasy_points_1999_week8"  "fantasy_points_1999_week9" 
  [9] "fantasy_points_1999_week10" "fantasy_points_1999_week11"
 [11] "fantasy_points_1999_week12" "fantasy_points_1999_week13"
 [13] "fantasy_points_1999_week14" "fantasy_points_1999_week15"
 [15] "fantasy_points_1999_week16" "fantasy_points_1999_week5" 
 [17] "fantasy_points_1999_week6"  "fantasy_points_1999_week17"
 [19] "fantasy_points_1999_week18" "fantasy_points_1999_week3" 
 [21] "fantasy_points_1999_week19" "fantasy_points_1999_week20"
 [23] "fantasy_points_1999_week21" "fantasy_points_2000_week1" 
 [25] "fantasy_points_2000_week12" "fantasy_points_2000_week14"
 [27] "fantasy_points_2000_week15" "fantasy_points_2000_week6" 
 [29] "fantasy_points_2000_week10" "fantasy_points_2000_week4" 
 [31] "fantasy_points_2000_week5"  "fantasy_points_2000_week7" 
 [33] "fantasy_points_2000_week8"  "fantasy_points_2000_week9" 
 [35] "fantasy_points_2000_week11" "fantasy_points_2000_week13"
 [37] "fantasy_points_2000_week2"  "fantasy_points_2000_week16"
 [39] "fantasy_points_2000_week17" "fantasy_points_2000_week3" 
 [41] "fantasy_points_2000_week18" "fantasy_points_2000_week19"
 [43] "fantasy_points_2000_week21" "fantasy_points_2000_week20"
 [45] "fantasy_points_2001_week15" "fantasy_points_2001_week17"
 [47] "fantasy_points_2001_week1"  "fantasy_points_2001_week3" 
 [49] "fantasy_points_2001_week4"  "fantasy_points_2001_week5" 
 [51] "fantasy_points_2001_week6"  "fantasy_points_2001_week9" 
 [53] "fantasy_points_2001_week11" "fantasy_points_2001_week12"
 [55] "fantasy_points_2001_week13" "fantasy_points_2001_week14"
 [57] "fantasy_points_2001_week16" "fantasy_points_2001_week2" 
 [59] "fantasy_points_2001_week7"  "fantasy_points_2001_week8" 
 [61] "fantasy_points_2001_week10" "fantasy_points_2001_week19"
 [63] "fantasy_points_2001_week18" "fantasy_points_2001_week20"
 [65] "fantasy_points_2001_week21" "fantasy_points_2002_week3" 
 [67] "fantasy_points_2002_week1"  "fantasy_points_2002_week2" 
 [69] "fantasy_points_2002_week4"  "fantasy_points_2002_week6" 
 [71] "fantasy_points_2002_week7"  "fantasy_points_2002_week8" 
 [73] "fantasy_points_2002_week9"  "fantasy_points_2002_week5" 
 [75] "fantasy_points_2002_week10" "fantasy_points_2002_week11"
 [77] "fantasy_points_2002_week12" "fantasy_points_2002_week13"
 [79] "fantasy_points_2002_week14" "fantasy_points_2002_week15"
 [81] "fantasy_points_2002_week16" "fantasy_points_2002_week17"
 [83] "fantasy_points_2002_week19" "fantasy_points_2002_week20"
 [85] "fantasy_points_2002_week21" "fantasy_points_2002_week18"
 [87] "fantasy_points_2003_week2"  "fantasy_points_2003_week4" 
 [89] "fantasy_points_2003_week5"  "fantasy_points_2003_week7" 
 [91] "fantasy_points_2003_week8"  "fantasy_points_2003_week9" 
 [93] "fantasy_points_2003_week10" "fantasy_points_2003_week11"
 [95] "fantasy_points_2003_week13" "fantasy_points_2003_week14"
 [97] "fantasy_points_2003_week15" "fantasy_points_2003_week17"
 [99] "fantasy_points_2003_week1"  "fantasy_points_2003_week3" 
[101] "fantasy_points_2003_week6"  "fantasy_points_2003_week12"
[103] "fantasy_points_2003_week16" "fantasy_points_2003_week18"
[105] "fantasy_points_2003_week19" "fantasy_points_2003_week20"
[107] "fantasy_points_2003_week21" "fantasy_points_2004_week2" 
[109] "fantasy_points_2004_week5"  "fantasy_points_2004_week6" 
[111] "fantasy_points_2004_week10" "fantasy_points_2004_week16"
[113] "fantasy_points_2004_week17" "fantasy_points_2004_week1" 
[115] "fantasy_points_2004_week3"  "fantasy_points_2004_week7" 
[117] "fantasy_points_2004_week8"  "fantasy_points_2004_week9" 
[119] "fantasy_points_2004_week11" "fantasy_points_2004_week12"
[121] "fantasy_points_2004_week13" "fantasy_points_2004_week14"
[123] "fantasy_points_2004_week15" "fantasy_points_2004_week4" 
[125] "fantasy_points_2004_week19" "fantasy_points_2004_week20"
[127] "fantasy_points_2004_week21" "fantasy_points_2004_week18"
[129] "fantasy_points_2005_week1"  "fantasy_points_2005_week2" 
[131] "fantasy_points_2005_week3"  "fantasy_points_2005_week4" 
[133] "fantasy_points_2005_week6"  "fantasy_points_2005_week7" 
[135] "fantasy_points_2005_week8"  "fantasy_points_2005_week10"
[137] "fantasy_points_2005_week11" "fantasy_points_2005_week13"
[139] "fantasy_points_2005_week14" "fantasy_points_2005_week15"
[141] "fantasy_points_2005_week16" "fantasy_points_2005_week17"
[143] "fantasy_points_2005_week5"  "fantasy_points_2005_week9" 
[145] "fantasy_points_2005_week12" "fantasy_points_2005_week18"
[147] "fantasy_points_2005_week19" "fantasy_points_2005_week20"
[149] "fantasy_points_2005_week21" "fantasy_points_2006_week4" 
[151] "fantasy_points_2006_week1"  "fantasy_points_2006_week2" 
[153] "fantasy_points_2006_week3"  "fantasy_points_2006_week10"
[155] "fantasy_points_2006_week11" "fantasy_points_2006_week12"
[157] "fantasy_points_2006_week13" "fantasy_points_2006_week14"
[159] "fantasy_points_2006_week5"  "fantasy_points_2006_week6" 
[161] "fantasy_points_2006_week7"  "fantasy_points_2006_week15"
[163] "fantasy_points_2006_week16" "fantasy_points_2006_week17"
[165] "fantasy_points_2006_week8"  "fantasy_points_2006_week9" 
[167] "fantasy_points_2006_week18" "fantasy_points_2006_week19"
[169] "fantasy_points_2006_week20" "fantasy_points_2006_week21"
[171] "fantasy_points_2007_week1"  "fantasy_points_2007_week2" 
[173] "fantasy_points_2007_week3"  "fantasy_points_2007_week5" 
[175] "fantasy_points_2007_week9"  "fantasy_points_2007_week16"
[177] "fantasy_points_2007_week17" "fantasy_points_2007_week14"
[179] "fantasy_points_2007_week4"  "fantasy_points_2007_week6" 
[181] "fantasy_points_2007_week7"  "fantasy_points_2007_week8" 
[183] "fantasy_points_2007_week10" "fantasy_points_2007_week11"
[185] "fantasy_points_2007_week12" "fantasy_points_2007_week13"
[187] "fantasy_points_2007_week15" "fantasy_points_2007_week19"
[189] "fantasy_points_2007_week21" "fantasy_points_2007_week18"
[191] "fantasy_points_2007_week20" "fantasy_points_2008_week8" 
[193] "fantasy_points_2008_week1"  "fantasy_points_2008_week2" 
[195] "fantasy_points_2008_week3"  "fantasy_points_2008_week4" 
[197] "fantasy_points_2008_week5"  "fantasy_points_2008_week6" 
[199] "fantasy_points_2008_week7"  "fantasy_points_2008_week14"
[201] "fantasy_points_2008_week10" "fantasy_points_2008_week11"
[203] "fantasy_points_2008_week12" "fantasy_points_2008_week13"
[205] "fantasy_points_2008_week15" "fantasy_points_2008_week16"
[207] "fantasy_points_2008_week17" "fantasy_points_2008_week9" 
[209] "fantasy_points_2008_week19" "fantasy_points_2008_week18"
[211] "fantasy_points_2008_week20" "fantasy_points_2008_week21"
[213] "fantasy_points_2009_week9"  "fantasy_points_2009_week11"
[215] "fantasy_points_2009_week2"  "fantasy_points_2009_week3" 
[217] "fantasy_points_2009_week5"  "fantasy_points_2009_week7" 
[219] "fantasy_points_2009_week12" "fantasy_points_2009_week13"
[221] "fantasy_points_2009_week14" "fantasy_points_2009_week15"
[223] "fantasy_points_2009_week16" "fantasy_points_2009_week17"
[225] "fantasy_points_2009_week1"  "fantasy_points_2009_week4" 
[227] "fantasy_points_2009_week8"  "fantasy_points_2009_week6" 
[229] "fantasy_points_2009_week10" "fantasy_points_2009_week18"
[231] "fantasy_points_2009_week19" "fantasy_points_2009_week20"
[233] "fantasy_points_2009_week21" "fantasy_points_2010_week2" 
[235] "fantasy_points_2010_week3"  "fantasy_points_2010_week4" 
[237] "fantasy_points_2010_week1"  "fantasy_points_2010_week7" 
[239] "fantasy_points_2010_week17" "fantasy_points_2010_week6" 
[241] "fantasy_points_2010_week8"  "fantasy_points_2010_week10"
[243] "fantasy_points_2010_week13" "fantasy_points_2010_week14"
[245] "fantasy_points_2010_week15" "fantasy_points_2010_week16"
[247] "fantasy_points_2010_week5"  "fantasy_points_2010_week20"
[249] "fantasy_points_2010_week12" "fantasy_points_2010_week11"
[251] "fantasy_points_2010_week18" "fantasy_points_2010_week19"
[253] "fantasy_points_2010_week21" "fantasy_points_2010_week9" 
[255] "fantasy_points_2011_week17" "fantasy_points_2011_week13"
[257] "fantasy_points_2011_week14" "fantasy_points_2011_week16"
[259] "fantasy_points_2011_week15" "fantasy_points_2011_week1" 
[261] "fantasy_points_2011_week2"  "fantasy_points_2011_week3" 
[263] "fantasy_points_2011_week4"  "fantasy_points_2011_week5" 
[265] "fantasy_points_2011_week6"  "fantasy_points_2011_week7" 
[267] "fantasy_points_2011_week9"  "fantasy_points_2011_week10"
[269] "fantasy_points_2011_week11" "fantasy_points_2011_week12"
[271] "fantasy_points_2011_week19" "fantasy_points_2011_week8" 
[273] "fantasy_points_2011_week18" "fantasy_points_2011_week20"
[275] "fantasy_points_2011_week21" "fantasy_points_2012_week12"
[277] "fantasy_points_2012_week13" "fantasy_points_2012_week2" 
[279] "fantasy_points_2012_week3"  "fantasy_points_2012_week4" 
[281] "fantasy_points_2012_week5"  "fantasy_points_2012_week7" 
[283] "fantasy_points_2012_week8"  "fantasy_points_2012_week9" 
[285] "fantasy_points_2012_week11" "fantasy_points_2012_week16"
[287] "fantasy_points_2012_week1"  "fantasy_points_2012_week6" 
[289] "fantasy_points_2012_week10" "fantasy_points_2012_week14"
[291] "fantasy_points_2012_week15" "fantasy_points_2012_week17"
[293] "fantasy_points_2012_week19" "fantasy_points_2012_week20"
[295] "fantasy_points_2012_week21" "fantasy_points_2012_week18"
[297] "fantasy_points_2013_week1"  "fantasy_points_2013_week2" 
[299] "fantasy_points_2013_week3"  "fantasy_points_2013_week4" 
[301] "fantasy_points_2013_week5"  "fantasy_points_2013_week7" 
[303] "fantasy_points_2013_week8"  "fantasy_points_2013_week9" 
[305] "fantasy_points_2013_week10" "fantasy_points_2013_week11"
[307] "fantasy_points_2013_week12" "fantasy_points_2013_week13"
[309] "fantasy_points_2013_week14" "fantasy_points_2013_week15"
[311] "fantasy_points_2013_week16" "fantasy_points_2013_week17"
[313] "fantasy_points_2013_week6"  "fantasy_points_2013_week19"
[315] "fantasy_points_2013_week20" "fantasy_points_2013_week21"
[317] "fantasy_points_2013_week18" "fantasy_points_2014_week3" 
[319] "fantasy_points_2014_week4"  "fantasy_points_2014_week16"
[321] "fantasy_points_2014_week17" "fantasy_points_2014_week1" 
[323] "fantasy_points_2014_week2"  "fantasy_points_2014_week5" 
[325] "fantasy_points_2014_week6"  "fantasy_points_2014_week7" 
[327] "fantasy_points_2014_week8"  "fantasy_points_2014_week9" 
[329] "fantasy_points_2014_week10" "fantasy_points_2014_week11"
[331] "fantasy_points_2014_week12" "fantasy_points_2014_week13"
[333] "fantasy_points_2014_week14" "fantasy_points_2014_week15"
[335] "fantasy_points_2014_week19" "fantasy_points_2014_week20"
[337] "fantasy_points_2014_week21" "fantasy_points_2014_week18"
[339] "fantasy_points_2015_week4"  "fantasy_points_2015_week5" 
[341] "fantasy_points_2015_week11" "fantasy_points_2015_week12"
[343] "fantasy_points_2015_week13" "fantasy_points_2015_week14"
[345] "fantasy_points_2015_week15" "fantasy_points_2015_week16"
[347] "fantasy_points_2015_week1"  "fantasy_points_2015_week2" 
[349] "fantasy_points_2015_week3"  "fantasy_points_2015_week6" 
[351] "fantasy_points_2015_week8"  "fantasy_points_2015_week9" 
[353] "fantasy_points_2015_week10" "fantasy_points_2015_week17"
[355] "fantasy_points_2015_week19" "fantasy_points_2015_week20"
[357] "fantasy_points_2015_week21" "fantasy_points_2015_week7" 
[359] "fantasy_points_2015_week18" "fantasy_points_2016_week5" 
[361] "fantasy_points_2016_week6"  "fantasy_points_2016_week7" 
[363] "fantasy_points_2016_week8"  "fantasy_points_2016_week10"
[365] "fantasy_points_2016_week11" "fantasy_points_2016_week12"
[367] "fantasy_points_2016_week13" "fantasy_points_2016_week14"
[369] "fantasy_points_2016_week15" "fantasy_points_2016_week16"
[371] "fantasy_points_2016_week17" "fantasy_points_2016_week19"
[373] "fantasy_points_2016_week20" "fantasy_points_2016_week21"
[375] "fantasy_points_2016_week1"  "fantasy_points_2016_week2" 
[377] "fantasy_points_2016_week3"  "fantasy_points_2016_week4" 
[379] "fantasy_points_2016_week9"  "fantasy_points_2016_week18"
[381] "fantasy_points_2017_week1"  "fantasy_points_2017_week2" 
[383] "fantasy_points_2017_week3"  "fantasy_points_2017_week4" 
[385] "fantasy_points_2017_week5"  "fantasy_points_2017_week6" 
[387] "fantasy_points_2017_week7"  "fantasy_points_2017_week8" 
[389] "fantasy_points_2017_week10" "fantasy_points_2017_week11"
[391] "fantasy_points_2017_week12" "fantasy_points_2017_week13"
[393] "fantasy_points_2017_week14" "fantasy_points_2017_week15"
[395] "fantasy_points_2017_week16" "fantasy_points_2017_week17"
[397] "fantasy_points_2017_week19" "fantasy_points_2017_week20"
[399] "fantasy_points_2017_week21" "fantasy_points_2017_week9" 
[401] "fantasy_points_2017_week18" "fantasy_points_2018_week1" 
[403] "fantasy_points_2018_week2"  "fantasy_points_2018_week3" 
[405] "fantasy_points_2018_week4"  "fantasy_points_2018_week5" 
[407] "fantasy_points_2018_week6"  "fantasy_points_2018_week7" 
[409] "fantasy_points_2018_week8"  "fantasy_points_2018_week9" 
[411] "fantasy_points_2018_week10" "fantasy_points_2018_week12"
[413] "fantasy_points_2018_week13" "fantasy_points_2018_week14"
[415] "fantasy_points_2018_week15" "fantasy_points_2018_week16"
[417] "fantasy_points_2018_week17" "fantasy_points_2018_week19"
[419] "fantasy_points_2018_week20" "fantasy_points_2018_week21"
[421] "fantasy_points_2018_week11" "fantasy_points_2018_week18"
[423] "fantasy_points_2019_week1"  "fantasy_points_2019_week2" 
[425] "fantasy_points_2019_week3"  "fantasy_points_2019_week4" 
[427] "fantasy_points_2019_week5"  "fantasy_points_2019_week6" 
[429] "fantasy_points_2019_week7"  "fantasy_points_2019_week8" 
[431] "fantasy_points_2019_week9"  "fantasy_points_2019_week11"
[433] "fantasy_points_2019_week12" "fantasy_points_2019_week13"
[435] "fantasy_points_2019_week14" "fantasy_points_2019_week15"
[437] "fantasy_points_2019_week16" "fantasy_points_2019_week17"
[439] "fantasy_points_2019_week18" "fantasy_points_2019_week10"
[441] "fantasy_points_2019_week19" "fantasy_points_2019_week20"
[443] "fantasy_points_2019_week21" "fantasy_points_2020_week1" 
[445] "fantasy_points_2020_week2"  "fantasy_points_2020_week3" 
[447] "fantasy_points_2020_week4"  "fantasy_points_2020_week5" 
[449] "fantasy_points_2020_week6"  "fantasy_points_2020_week7" 
[451] "fantasy_points_2020_week8"  "fantasy_points_2020_week9" 
[453] "fantasy_points_2020_week10" "fantasy_points_2020_week11"
[455] "fantasy_points_2020_week12" "fantasy_points_2020_week14"
[457] "fantasy_points_2020_week15" "fantasy_points_2020_week16"
[459] "fantasy_points_2020_week17" "fantasy_points_2020_week18"
[461] "fantasy_points_2020_week19" "fantasy_points_2020_week20"
[463] "fantasy_points_2020_week21" "fantasy_points_2020_week13"
[465] "fantasy_points_2021_week1"  "fantasy_points_2021_week2" 
[467] "fantasy_points_2021_week3"  "fantasy_points_2021_week4" 
[469] "fantasy_points_2021_week5"  "fantasy_points_2021_week6" 
[471] "fantasy_points_2021_week7"  "fantasy_points_2021_week8" 
[473] "fantasy_points_2021_week10" "fantasy_points_2021_week11"
[475] "fantasy_points_2021_week12" "fantasy_points_2021_week13"
[477] "fantasy_points_2021_week14" "fantasy_points_2021_week15"
[479] "fantasy_points_2021_week16" "fantasy_points_2021_week17"
[481] "fantasy_points_2021_week18" "fantasy_points_2021_week19"
[483] "fantasy_points_2021_week20" "fantasy_points_2021_week9" 
[485] "fantasy_points_2021_week21" "fantasy_points_2021_week22"
[487] "fantasy_points_2022_week1"  "fantasy_points_2022_week2" 
[489] "fantasy_points_2022_week3"  "fantasy_points_2022_week4" 
[491] "fantasy_points_2022_week5"  "fantasy_points_2022_week6" 
[493] "fantasy_points_2022_week7"  "fantasy_points_2022_week8" 
[495] "fantasy_points_2022_week9"  "fantasy_points_2022_week10"
[497] "fantasy_points_2022_week12" "fantasy_points_2022_week13"
[499] "fantasy_points_2022_week14" "fantasy_points_2022_week15"
[501] "fantasy_points_2022_week16" "fantasy_points_2022_week17"
[503] "fantasy_points_2022_week18" "fantasy_points_2022_week19"
[505] "fantasy_points_2022_week11" "fantasy_points_2022_week20"
[507] "fantasy_points_2022_week21" "fantasy_points_2022_week22"
[509] "fantasy_points_2023_week1"  "fantasy_points_2023_week4" 
[511] "fantasy_points_2023_week7"  "fantasy_points_2023_week11"
[513] "fantasy_points_2023_week14" "fantasy_points_2023_week16"
[515] "fantasy_points_2023_week13" "fantasy_points_2023_week15"
[517] "fantasy_points_2023_week17" "fantasy_points_2023_week19"
[519] "fantasy_points_2023_week2"  "fantasy_points_2023_week3" 
[521] "fantasy_points_2023_week5"  "fantasy_points_2023_week6" 
[523] "fantasy_points_2023_week8"  "fantasy_points_2023_week12"
[525] "fantasy_points_2023_week18" "fantasy_points_2023_week10"
[527] "fantasy_points_2023_week21" "fantasy_points_2023_week22"
[529] "fantasy_points_2023_week9"  "fantasy_points_2023_week20"

3.18 Transform Data from Wide to Long

Conversely, we can also restructure data from wide to long.

Original data:

Code
dataWide <- nfl_actualStats_offense_weekly %>% 
  select(player_id, player_display_name, season, week, recent_team, opponent_team)

dim(dataWide)
[1] 129739      6
Code
names(dataWide)
[1] "player_id"           "player_display_name" "season"             
[4] "week"                "recent_team"         "opponent_team"      

Data in long form, transformed from wide form using tidyverse:

Code
dataLong <- dataWide %>% 
  pivot_longer(
    cols = c(recent_team, opponent_team),
    names_to = "role",
    values_to = "team")

dim(dataLong)
[1] 259478      6
Code
names(dataLong)
[1] "player_id"           "player_display_name" "season"             
[4] "week"                "role"                "team"               

3.19 Calculations

3.19.1 Historical Actual Player Statistics

In addition to week-by-week actual player statistics, we can also compute historical actual player statistics as a function of different timeframes, including season-by-season and career statistics.

3.19.1.1 Career Statistics

First, we can compute the players’ career statistics using the calculate_player_stats(), calculate_player_stats_def(), and calculate_player_stats_kicking() functions from the nflfastR package for offensive players, defensive players, and kickers, respectively.

Note 3.3: Calculating players’ career statistics

Note: the following code takes a while to run.

Code
nfl_actualStats_offense_career <- nflfastR::calculate_player_stats(
  nfl_pbp,
  weekly = FALSE)

nfl_actualStats_defense_career <- nflfastR::calculate_player_stats_def(
  nfl_pbp,
  weekly = FALSE)

nfl_actualStats_kicking_career <- nflfastR::calculate_player_stats_kicking(
  nfl_pbp,
  weekly = FALSE)

3.19.1.2 Season-by-Season Statistics

Second, we can compute the players’ season-by-season statistics.

Code
seasons <- unique(nfl_pbp$season)

nfl_pbp_seasonalList <- list()
nfl_actualStats_offense_seasonalList <- list()
nfl_actualStats_defense_seasonalList <- list()
nfl_actualStats_kicking_seasonalList <- list()
Note 3.4: Calculating players’ season-by-season statistics

Note: the following code takes a while to run.

Code
pb <- txtProgressBar(
  min = 0,
  max = length(seasons),
  style = 3)

for(i in 1:length(seasons)){
  # Subset play-by-play data by season
  nfl_pbp_seasonalList[[i]] <- nfl_pbp %>% 
    filter(season == seasons[i])
  
  # Compute actual statistics by season
  nfl_actualStats_offense_seasonalList[[i]] <- 
    nflfastR::calculate_player_stats(
      nfl_pbp_seasonalList[[i]],
      weekly = FALSE)

  nfl_actualStats_defense_seasonalList[[i]] <- 
    nflfastR::calculate_player_stats_def(
      nfl_pbp_seasonalList[[i]],
      weekly = FALSE)

  nfl_actualStats_kicking_seasonalList[[i]] <- 
    nflfastR::calculate_player_stats_kicking(
      nfl_pbp_seasonalList[[i]],
      weekly = FALSE)

  nfl_actualStats_offense_seasonalList[[i]]$season <- seasons[i]
  nfl_actualStats_defense_seasonalList[[i]]$season <- seasons[i]
  nfl_actualStats_kicking_seasonalList[[i]]$season <- seasons[i]
  
  print(
    paste("Completed computing projections for season: ", seasons[i], sep = ""))

  # Update the progress bar
  setTxtProgressBar(pb, i)
}

# Close the progress bar
close(pb)

nfl_actualStats_offense_seasonal <- nfl_actualStats_offense_seasonalList %>% 
  bind_rows()
nfl_actualStats_defense_seasonal <- nfl_actualStats_defense_seasonalList %>% 
  bind_rows()
nfl_actualStats_kicking_seasonal <- nfl_actualStats_kicking_seasonalList %>% 
  bind_rows()

3.19.1.3 Week-by-Week Statistics

We already load players’ week-by-week statistics above. Nevertheless, we could compute players’ weekly statistics from the play-by-play data using the following syntax:

Code
nfl_actualStats_offense_weekly <- nflfastR::calculate_player_stats(
  nfl_pbp,
  weekly = TRUE)

nfl_actualStats_defense_weekly <- nflfastR::calculate_player_stats_def(
  nfl_pbp,
  weekly = TRUE)

nfl_actualStats_kicking_weekly <- nflfastR::calculate_player_stats_kicking(
  nfl_pbp,
  weekly = TRUE)

3.19.2 Historical Actual Fantasy Points

Specify scoring settings:

3.19.2.1 Weekly

3.19.2.2 Seasonal

3.19.2.3 Career

3.19.3 Player Age

Code
# Reshape from wide to long format
nfl_actualStats_offense_weekly_long <- nfl_actualStats_offense_weekly %>% 
  pivot_longer(
    cols = c(recent_team, opponent_team),
    names_to = "role",
    values_to = "team")

# Perform separate inner join operations for the home_team and away_team
nfl_actualStats_offense_weekly_home <- inner_join(
  nfl_actualStats_offense_weekly_long,
  nfl_schedules,
  by = c("season","week","team" = "home_team")) %>% 
  mutate(home_away = "home_team")

nfl_actualStats_offense_weekly_away <- inner_join(
  nfl_actualStats_offense_weekly_long,
  nfl_schedules,
  by = c("season","week","team" = "away_team")) %>% 
  mutate(home_away = "away_team")

nfl_actualStats_defense_weekly_home <- inner_join(
  nfl_actualStats_defense_weekly,
  nfl_schedules,
  by = c("season","week","team" = "home_team")) %>% 
  mutate(home_away = "home_team")

nfl_actualStats_defense_weekly_away <- inner_join(
  nfl_actualStats_defense_weekly,
  nfl_schedules,
  by = c("season","week","team" = "away_team")) %>% 
  mutate(home_away = "away_team")

nfl_actualStats_kicking_weekly_home <- inner_join(
  nfl_actualStats_kicking_weekly,
  nfl_schedules,
  by = c("season","week","team" = "home_team")) %>% 
  mutate(home_away = "home_team")

nfl_actualStats_kicking_weekly_away <- inner_join(
  nfl_actualStats_kicking_weekly,
  nfl_schedules,
  by = c("season","week","team" = "away_team")) %>% 
  mutate(home_away = "away_team")

# Combine the results of the join operations
nfl_actualStats_offense_weekly_schedules_long <- bind_rows(
  nfl_actualStats_offense_weekly_home,
  nfl_actualStats_offense_weekly_away)

nfl_actualStats_defense_weekly_schedules_long <- bind_rows(
  nfl_actualStats_defense_weekly_home,
  nfl_actualStats_defense_weekly_away)

nfl_actualStats_kicking_weekly_schedules_long <- bind_rows(
  nfl_actualStats_kicking_weekly_home,
  nfl_actualStats_kicking_weekly_away)

# Reshape from long to wide
player_game_gameday_offense <- nfl_actualStats_offense_weekly_schedules_long %>%
  distinct(player_id, season, week, game_id, home_away, team, gameday) %>% #, .keep_all = TRUE
  pivot_wider(
    names_from = home_away,
    values_from = team)

player_game_gameday_defense <- nfl_actualStats_defense_weekly_schedules_long %>%
  distinct(player_id, season, week, game_id, home_away, team, gameday) %>% #, .keep_all = TRUE
  pivot_wider(
    names_from = home_away,
    values_from = team)

player_game_gameday_kicking <- nfl_actualStats_kicking_weekly_schedules_long %>%
  distinct(player_id, season, week, game_id, home_away, team, gameday) %>% #, .keep_all = TRUE
  pivot_wider(
    names_from = home_away,
    values_from = team)

# Merge player birthdate and the game date
player_game_birthdate_gameday_offense <- left_join(
  player_game_gameday_offense,
  unique(nfl_players[,c("gsis_id","birth_date")]),
  by = c("player_id" = "gsis_id")
)

player_game_birthdate_gameday_defense <- left_join(
  player_game_gameday_defense,
  unique(nfl_players[,c("gsis_id","birth_date")]),
  by = c("player_id" = "gsis_id")
)

player_game_birthdate_gameday_kicking <- left_join(
  player_game_gameday_kicking,
  unique(nfl_players[,c("gsis_id","birth_date")]),
  by = c("player_id" = "gsis_id")
)

player_game_birthdate_gameday_offense$birth_date <- ymd(player_game_birthdate_gameday_offense$birth_date)
player_game_birthdate_gameday_offense$gameday <- ymd(player_game_birthdate_gameday_offense$gameday)

player_game_birthdate_gameday_defense$birth_date <- ymd(player_game_birthdate_gameday_defense$birth_date)
player_game_birthdate_gameday_defense$gameday <- ymd(player_game_birthdate_gameday_defense$gameday)

player_game_birthdate_gameday_kicking$birth_date <- ymd(player_game_birthdate_gameday_kicking$birth_date)
player_game_birthdate_gameday_kicking$gameday <- ymd(player_game_birthdate_gameday_kicking$gameday)

# Calculate player's age for a given week as the difference between their birthdate and the game date
player_game_birthdate_gameday_offense$age <- interval(
  start = player_game_birthdate_gameday_offense$birth_date,
  end = player_game_birthdate_gameday_offense$gameday
) %>% 
  time_length(unit = "years")

player_game_birthdate_gameday_defense$age <- interval(
  start = player_game_birthdate_gameday_defense$birth_date,
  end = player_game_birthdate_gameday_defense$gameday
) %>% 
  time_length(unit = "years")

player_game_birthdate_gameday_kicking$age <- interval(
  start = player_game_birthdate_gameday_kicking$birth_date,
  end = player_game_birthdate_gameday_kicking$gameday
) %>% 
  time_length(unit = "years")

# Merge with player info
player_age_offense <-  left_join(
  player_game_birthdate_gameday_offense,
  nfl_players %>% select(-birth_date, -season),
  by = c("player_id" = "gsis_id"))

player_age_defense <-  left_join(
  player_game_birthdate_gameday_defense,
  nfl_players %>% select(-birth_date, -season),
  by = c("player_id" = "gsis_id"))

player_age_kicking <-  left_join(
  player_game_birthdate_gameday_kicking,
  nfl_players %>% select(-birth_date, -season),
  by = c("player_id" = "gsis_id"))

# Add game_id to weekly stats to facilitate merging
nfl_actualStats_game_offense_weekly <- nfl_actualStats_offense_weekly %>% 
  left_join(
    player_age_offense[,c("season","week","player_id","game_id")],
    by = c("season","week","player_id"))

nfl_actualStats_game_defense_weekly <- nfl_actualStats_defense_weekly %>% 
  left_join(
    player_age_offense[,c("season","week","player_id","game_id")],
    by = c("season","week","player_id"))

nfl_actualStats_game_kicking_weekly <- nfl_actualStats_kicking_weekly %>% 
  left_join(
    player_age_offense[,c("season","week","player_id","game_id")],
    by = c("season","week","player_id"))

# Merge with player weekly stats
player_age_stats_offense <- left_join(
  player_age_offense %>% select(-position, -position_group),
  nfl_actualStats_game_offense_weekly,
  by = c(c("season","week","player_id","game_id")))

player_age_stats_defense <- left_join(
  player_age_defense %>% select(-position, -position_group),
  nfl_actualStats_game_defense_weekly,
  by = c(c("season","week","player_id","game_id")))

player_age_stats_kicking <- left_join(
  player_age_kicking %>% select(-position, -position_group),
  nfl_actualStats_game_kicking_weekly,
  by = c(c("season","week","player_id","game_id")))

player_age_stats_offense$years_of_experience <- as.integer(player_age_stats_offense$years_of_experience)
player_age_stats_defense$years_of_experience <- as.integer(player_age_stats_defense$years_of_experience)
player_age_stats_kicking$years_of_experience <- as.integer(player_age_stats_kicking$years_of_experience)

# Merge player info with seasonal stats
player_seasonal_offense <- left_join(
  nfl_actualStats_offense_seasonal,
  nfl_players %>% select(-position, -position_group, -season),
  by = c("player_id" = "gsis_id")
)

player_seasonal_defense <- left_join(
  nfl_actualStats_defense_seasonal,
  nfl_players %>% select(-position, -position_group, -season),
  by = c("player_id" = "gsis_id")
)

player_seasonal_kicking <- left_join(
  nfl_actualStats_kicking_seasonal,
  nfl_players %>% select(-position, -position_group, -season),
  by = c("player_id" = "gsis_id")
)

# Calculate age
season_startdate <- nfl_schedules %>% 
  group_by(season) %>% 
  summarise(startdate = min(gameday, na.rm = TRUE))

player_seasonal_offense <- player_seasonal_offense %>% 
  left_join(
    season_startdate,
    by = "season"
  )

player_seasonal_defense <- player_seasonal_defense %>% 
  left_join(
    season_startdate,
    by = "season"
  )

player_seasonal_kicking <- player_seasonal_kicking %>% 
  left_join(
    season_startdate,
    by = "season"
  )

player_seasonal_offense$age <- interval(
  start = player_seasonal_offense$birth_date,
  end = player_seasonal_offense$startdate
) %>% 
  time_length(unit = "years")

player_seasonal_defense$age <- interval(
  start = player_seasonal_defense$birth_date,
  end = player_seasonal_defense$startdate
) %>% 
  time_length(unit = "years")

player_seasonal_kicking$age <- interval(
  start = player_seasonal_kicking$birth_date,
  end = player_seasonal_kicking$startdate
) %>% 
  time_length(unit = "years")

3.20 Plotting

3.20.1 Rushing Yards per Carry By Player Age

Code
# Prepare Data
rushing_attempts <- nfl_pbp %>% 
  dplyr::filter(
    season_type == "REG") %>% 
    filter(
      rush == 1,
      rush_attempt == 1,
      qb_scramble == 0,
      qb_dropback == 0,
      !is.na(rushing_yards))

rb_yardsPerCarry <- rushing_attempts %>% 
  group_by(rusher_id, season) %>% 
  summarise(
    ypc = mean(rushing_yards, na.rm = TRUE),
    rush_attempts = n(),
    .groups = "drop") %>% 
  ungroup() %>% 
  left_join(
    nfl_players %>% select(-season),
    by = c("rusher_id" = "gsis_id")
  ) %>% 
  filter(
    position_group == "RB",
    rush_attempts >= 50) %>% 
  left_join(
    season_startdate,
    by = "season"
  )

rb_yardsPerCarry$age <- interval(
  start = rb_yardsPerCarry$birth_date,
  end = rb_yardsPerCarry$startdate
) %>% 
  time_length(unit = "years")

# Create Plot
ggplot2::ggplot(
  data = rb_yardsPerCarry,
  ggplot2::aes(
    x = age,
    y = ypc)) +
  ggplot2::geom_point() +
  ggplot2::geom_smooth() +
  ggplot2::labs(
    x = "Rushing Back Age (years)",
    y = "Rushing Yards per Carry/season",
    title = "2023 NFL Rushing Yards Per Carry per Season by Player Age",
    subtitle = "(minimum 50 rushing attempts)"
  ) +
  ggplot2::theme_classic()
Figure 3.1: 2023 NFL Rushing Yards Per Carry per Season by Player Age
Code
# Subset Data
rb_seasonal <- player_seasonal_offense %>% 
  filter(position_group == "RB")

# Create Plot
ggplot2::ggplot(
  data = rb_seasonal,
  ggplot2::aes(
    x = age,
    y = rushing_epa)) +
  ggplot2::geom_point() +
  ggplot2::geom_smooth() +
  ggplot2::labs(
    x = "Rushing Back Age (years)",
    y = "Rushing EPA/season",
    title = "2023 NFL Rushing Expected Points Added (EPA) per Season by Player Age"
  ) +
  ggplot2::theme_classic()
Figure 3.2: 2023 NFL Rushing Expected Points Added (EPA) per Season by Player Age

3.20.2 Defensive and Offensive EPA per Play

Expected points added (EPA) per play by the team with possession.

Code
pbp_regularSeason <- nfl_pbp %>% 
  dplyr::filter(
    season == 2023,
    season_type == "REG") %>%
  dplyr::filter(!is.na(posteam) & (rush == 1 | pass == 1))

epa_offense <- pbp_regularSeason %>%
  dplyr::group_by(team = posteam) %>%
  dplyr::summarise(off_epa = mean(epa, na.rm = TRUE))

epa_defense <- pbp_regularSeason %>%
  dplyr::group_by(team = defteam) %>%
  dplyr::summarise(def_epa = mean(epa, na.rm = TRUE))

epa_combined <- epa_offense %>%
  dplyr::inner_join(epa_defense, by = "team")

ggplot2::ggplot(
  data = epa_combined,
  ggplot2::aes(
    x = off_epa,
    y = def_epa)) +
  nflplotR::geom_mean_lines(
    ggplot2::aes(
      x0 = off_epa ,
      y0 = def_epa)) +
  nflplotR::geom_nfl_logos(
    ggplot2::aes(
      team_abbr = team),
      width = 0.065,
      alpha = 0.7) +
  ggplot2::labs(
    x = "Offense EPA/play",
    y = "Defense EPA/play",
    title = "2023 NFL Offensive and Defensive EPA per Play"
  ) +
  ggplot2::theme_classic() +
  ggplot2::scale_y_reverse()
Figure 3.3: 2023 NFL Offensive and Defensive EPA per Play

3.21 Session Info

At the end of each chapter in which R code is used, I provide the session information, which describes the system and operating system the code was run on and the versions of each package. That way, if you get different results from me, you can see which differ, to help with reproducibility. If you run the (all of) the exact same code as is provided in the text, in the exact same order, with the exact same setup (platform, operating system, package versions, etc.), you should get the exact same answer as is in the text. That is the idea of reproducibility—getting the exact same result with the exact same inputs. Reproducibility is crucial for studies to achieve greater confidence in their findings and to ensure better replicability of findings across studies.

Code
sessionInfo()
R version 4.4.1 (2024-06-14)
Platform: x86_64-pc-linux-gnu
Running under: Ubuntu 22.04.4 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so;  LAPACK version 3.10.0

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   

time zone: UTC
tzcode source: system (glibc)

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] here_1.0.1             forcats_1.0.0          stringr_1.5.1         
 [4] dplyr_1.1.4            purrr_1.0.2            readr_2.1.5           
 [7] tidyr_1.3.1            tibble_3.2.1           ggplot2_3.5.1         
[10] tidyverse_2.0.0        lubridate_1.9.3        progressr_0.14.0      
[13] nflplotR_1.3.1         nfl4th_1.0.4           nflfastR_4.6.1        
[16] nflreadr_1.4.0         ffanalytics_3.1.2.0001

loaded via a namespace (and not attached):
 [1] gtable_0.3.5      xfun_0.45         httr2_1.0.1       htmlwidgets_1.6.4
 [5] lattice_0.22-6    tzdb_0.4.0        vctrs_0.6.5       tools_4.4.1      
 [9] generics_0.1.3    curl_5.2.1        parallel_4.4.1    fansi_1.0.6      
[13] pkgconfig_2.0.3   Matrix_1.7-0      data.table_1.15.4 readxl_1.4.3     
[17] gt_0.10.1         lifecycle_1.0.4   farver_2.1.2      compiler_4.4.1   
[21] munsell_0.5.1     janitor_2.2.0     codetools_0.2-20  snakecase_0.11.1 
[25] rrapply_1.2.7     htmltools_0.5.8.1 yaml_2.3.8        pillar_1.9.0     
[29] furrr_0.3.1       cachem_1.1.0      magick_2.8.3      nlme_3.1-164     
[33] parallelly_1.37.1 tidyselect_1.2.1  rvest_1.0.4       digest_0.6.36    
[37] stringi_1.8.4     future_1.33.2     listenv_0.9.1     labeling_0.4.3   
[41] splines_4.4.1     rprojroot_2.0.4   fastmap_1.2.0     grid_4.4.1       
[45] colorspace_2.1-0  cli_3.6.3         magrittr_2.0.3    utf8_1.2.4       
[49] withr_3.0.0       scales_1.3.0      backports_1.5.0   rappdirs_0.3.3   
[53] ggpath_1.0.1      xgboost_1.7.7.1   timechange_0.3.0  rmarkdown_2.27   
[57] httr_1.4.7        globals_0.16.3    cellranger_1.1.0  hms_1.1.3        
[61] memoise_2.0.1     evaluate_0.24.0   knitr_1.47        mgcv_1.9-1       
[65] rlang_1.1.4       Rcpp_1.0.12       glue_1.7.0        xml2_1.3.6       
[69] jsonlite_1.8.8    R6_2.5.1          fastrmodels_1.0.2

Feedback

Please consider providing feedback about this textbook, so that I can make it as helpful as possible. You can provide feedback at the following link: https://forms.gle/LsnVKwqmS1VuxWD18

Email Notification

The online version of this book will remain open access. If you want to know when the print version of the book is for sale, enter your email below so I can let you know.