### Install nflseedR Development Version from GitHub Source: https://github.com/nflverse/nflseedr/blob/master/README.md Install the development version of nflseedR from GitHub, which may include bug fixes or new features. Ensure 'pak' is installed first. ```r if (!requireNamespace("pak")) install.packages("pak") pak::pak("nflverse/nflseedR") ``` -------------------------------- ### Code Examples Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/MANIFEST.txt A collection of over 100 practical code examples demonstrating basic usage, custom implementations, and advanced workflows. ```APIDOC ## Code Examples ### Description NFLSeedr provides a rich set of over 100 code examples to illustrate various usage patterns and implementation techniques. ### Files - 09-usage-patterns.md (330 lines, 11KB) ### Example Categories - Basic usage patterns - Custom model implementations - Parallel processing setup - Data analysis workflows - Output formatting ``` -------------------------------- ### View and Extend Example Team Roster Data Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/04-api-schedule.md Load and inspect the example team roster data. This data serves as a template for simulations and can be extended with custom columns like ELO ratings. ```r library(nflseedR) # View example data str(sims_teams_example) # Extend with custom columns library(dplyr) my_teams <- sims_teams_example %>% mutate(elo = rnorm(n(), 1500, 150)) # Pass to simulation sim <- nfl_simulations( games = sims_games_example, simulations = 10 ) ``` -------------------------------- ### Search Documentation Example Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/INDEX.md Demonstrates how to search for specific terms within the documentation, such as function names, parameter names, data types, error messages, or concepts. ```text simulate_nfl tiebreaker_depth nflseedR_simulation Invalid parallel processing ``` -------------------------------- ### Install nflseedR from R-universe Source: https://github.com/nflverse/nflseedr/blob/master/README.md Install the development version of nflseedR from the nflverse R-universe repository. ```r install.packages("nflseedR", repos = c("https://nflverse.r-universe.dev", getOption("repos"))) ``` -------------------------------- ### View and Use Example Game Schedule Data Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/04-api-schedule.md Load and inspect the example game schedule data. This data is used for validating simulation functions and running test simulations. ```r library(nflseedR) # View example data str(sims_games_example) # Verify a custom function simulations_verify_fct(my_function, games = sims_games_example) # Run test simulation sim <- nfl_simulations( games = sims_games_example, simulations = 10 ) ``` -------------------------------- ### Install nflseedR from CRAN Source: https://github.com/nflverse/nflseedr/blob/master/README.md Install the stable version of the nflseedR package from CRAN. ```r install.packages("nflseedR") ``` -------------------------------- ### Division Ranking Flow Example Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/08-implementation-guide.md Illustrates the hierarchical process of ranking teams within a division, including filtering by win percentage and applying tiebreaker rules. ```text Teams grouped by division ├─ Division East │ ├─ Filter: max(win_pct) │ ├─ Tie check: n() == 1? │ │ ├─ Yes: Assign div_rank = 1 │ │ └─ No: Apply head-to-head tiebreaker │ │ └─ Continue with remaining tied teams │ └─ Repeat for div_rank 2, 3, 4 ├─ Division West │ └─ (same process) └─ ... ``` -------------------------------- ### Configuration Parameters Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/MANIFEST.txt Details on the various configuration parameters available for NFLSeedr, including simulation, standings, and processing setups. ```APIDOC ## Configuration Parameters ### Description NFLSeedr offers extensive configuration options to customize simulations, standings calculations, and processing. ### Files - 06-configuration.md (340 lines, 9.6KB) ### Documented Parameters (50+) - Simulation parameters - Standings parameters - Tiebreaker configuration - Parallel processing setup - Random number generation - Progress reporting - Custom function requirements ``` -------------------------------- ### Configure Progress Handlers Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md Sets up different handlers for progress reporting. Choose 'progress' for an interactive bar, 'void' for no output, or combine multiple handlers for custom reporting. ```r # Interactive console progress bar handlers("progress") # Quiet (no progress) handlers("void") # Multiple handlers handlers( handler_progress(format = "Progress: [:bar] :percent"), handler_txtProgressBar() ) ``` -------------------------------- ### Parallel Processing with Multiple Cores Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Set up and utilize multiple CPU cores for faster simulations using the `future` package. Ensure to return to sequential processing after parallel tasks are complete. ```r library(nflseedR) library(future) # Set up parallel processing plan(multisession, workers = 8) # Reproducible random number generation set.seed(12345, kind = "L'Ecuyer-CMRG") # Run simulation sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 10000, sims_per_round = 500 # 20 parallel rounds ) # Return to sequential plan(sequential) ``` -------------------------------- ### Run NFL Simulations with Default ELO Computation Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md This snippet demonstrates how to run NFL simulations using the default ELO computation method. It requires the 'nflseedR' library and a data frame of game schedules. Adjust the number of simulations and parallel chunks as needed. ```r library(nflseedR) # Using default ELO computation sim <- nfl_simulations( games = nflseedR::sims_games_example, simulations = 1000, chunks = 10 ) ``` -------------------------------- ### Generate and Save NFL Simulation Summary Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md This code snippet demonstrates how to generate an NFL simulation using `simulate_nfl`, obtain a summary table using the `summary` method, and then save this summary as an HTML file using `gt::gtsave`. The summary method itself does not take additional parameters; formatting is handled by the simulation object and graphics packages. ```r sim <- simulate_nfl(2022, simulations = 100) # Generate summary (returns gt table) tbl <- summary(sim) # View in RStudio viewer or browser print(tbl) # Save to HTML file gt::gtsave(tbl, "simulation_summary.html") ``` -------------------------------- ### R: Custom compute_results function signature Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/07-errors.md When providing a custom `compute_results` function, ensure it accepts 'teams', 'games', and 'week_num' as arguments. This example shows the required signature. ```r my_compute <- function(teams, games, week_num, ...) { # implementation list(teams = teams, games = games) } ``` -------------------------------- ### R: Custom compute_results function return format Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/07-errors.md The custom `compute_results` function must return a list containing 'teams' and 'games' elements. This example demonstrates the correct return format. ```r list(teams = teams, games = games) ``` -------------------------------- ### Get Current Playoff Bracket if Season Ended Today Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Determines the current playoff bracket and seeding as if the season concluded on the current date. Returns a single 'simulation' with current standings. ```r # Get current playoff bracket standings <- simulate_nfl( nfl_season = 2022, if_ended_today = TRUE ) # Result has 1 "simulation" with current standings current_seeds <- standings$standings %>% filter(!is.na(seed)) %>% arrange(seed) ``` -------------------------------- ### Configure Default Parallel Plan via Environment Variable Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md Set the default parallelization plan using an environment variable. This can be done in the shell or in an .Renviron file. ```bash # In shell or .Renviron export R_FUTURE_PLAN="multisession" ``` -------------------------------- ### R: Custom compute_results function game modification condition Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/07-errors.md When modifying game results within a custom `compute_results` function, ensure modifications are only applied to the correct week and for non-existent results. This example shows the conditional logic. ```r week == week_num && is.na(result) ``` -------------------------------- ### Generate and Display Summary Table Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Use the `summary()` method on a simulation object to create a formatted HTML table. This table can be printed directly or saved to an HTML file. ```r library(nflseedR) sim <- simulate_nfl(2022, simulations = 100) # Generate summary HTML table summary_table <- summary(sim) # Display in RStudio print(summary_table) # Save to file gt::gtsave(summary_table, "nfl_simulation.html") ``` -------------------------------- ### Simulate NFL Season with Defaults Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Simulates a single NFL season using default settings. Useful for a quick overview of potential season outcomes. ```r library(nflseedR) # Simulate a single season with defaults sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 1000 ) # View overall results head(sim$overall) # Get Super Bowl winners sb_winners <- sim$standings %>% filter(!is.na(exit) & exit == max(exit)) ``` -------------------------------- ### Progress Reporting for Simulations Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Enable progress updates during simulations using the `progressr` package. This can be done globally or locally using `with_progress` for better control. ```r library(nflseedR) library(progressr) # Enable progress updates handlers(global = TRUE) # Run simulation - will show progress sim <- simulate_nfl( nfl_season = 2022, simulations = 5000 ) # Or use with_progress for local control sim <- with_progress({ simulate_nfl(2022, fresh_season = TRUE, simulations = 5000) }) ``` -------------------------------- ### ELO-Based Custom Simulation Model Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Implement a custom ELO-based simulation model with adjustable parameters like k-factor and home advantage. Ensure the custom model is validated before running simulations. ```r library(nflseedR) library(dplyr) my_elo_model <- function(teams, games, week_num, k_factor = 20, home_advantage = 20, ...) { # Filter to current week unplayed games current <- games %>% filter(week == week_num & is.na(result)) if (nrow(current) == 0) { return(list(teams = teams, games = games)) } # Join ELO ratings ratings <- teams %>% select(sim, team, elo) current <- current %>% left_join(ratings, by = c("sim" = "sim", "away_team" = "team")) %>% rename(away_elo = elo) %>% left_join(ratings, by = c("sim" = "sim", "home_team" = "team")) %>% rename(home_elo = elo) # Compute probabilities and results current <- current %>% mutate( elo_diff = home_elo - away_elo + home_advantage, wp = 1 / (1 + 10^(-elo_diff / 400)), result = ifelse( game_type == "REG", rnorm(n(), elo_diff / 25, 13), rnorm(n(), elo_diff / 25, 13) ) ) %>% mutate(result = as.integer(round(result))) # Update ELO ratings # ... (elo shift calculation) ... # Merge back games <- games %>% rows_update(current %>% select(sim, game_id, result), by = c("sim", "game_id")) list(teams = teams, games = games) } # Validate before using simulations_verify_fct(my_elo_model) # Run simulation sim <- simulate_nfl( nfl_season = 2022, process_games = my_elo_model, k_factor = 25, simulations = 100 ) ``` -------------------------------- ### Utility Modules in R Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/08-implementation-guide.md Overview of utility R modules in nflSeedR, covering schedule generation, output formatting, percentage formatting, data loading, and documentation. ```r # nfl_regular_season.R - Schedule generation # `nfl_regular_season()` - Compute next season matchups # Applies NFL rotation rules # standings_prettify.R - Display formatting # `nfl_standings_prettify()` - Format for HTML output # fmt_pct_special.R - Percentage formatting # `fmt_pct_special()` - Format numeric as percentage # load_sharpe_games.R - Data loading (deprecated) # `load_sharpe_games()` - Legacy wrapper # data_doc.R - Data documentation # `divisions` - Team/conference/division mapping # Example data and data dictionaries ``` -------------------------------- ### API Reference - Simulation Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/MANIFEST.txt Documentation for the simulation API, including function signatures, parameter details, return values, and error conditions. ```APIDOC ## API Reference - Simulation ### Description Enables running simulations with configurable parameters. ### Files - 03-api-simulation.md (420 lines, 14KB) ### Content - Function signatures - Parameter documentation - Return value documentation - Error conditions - Code examples ``` -------------------------------- ### Compare Simulation Models Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Run simulations with both the default model and a custom model, then use `dplyr::full_join` to compare their playoff prediction outcomes. ```r library(nflseedR) library(dplyr) # Run simulations with different models sim_default <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 1000 ) sim_custom <- simulate_nfl( nfl_season = 2022, process_games = my_model, fresh_season = TRUE, simulations = 1000 ) # Compare results comparison <- full_join( sim_default$overall %>% select(team, playoff) %>% rename(playoff_default = playoff), sim_custom$overall %>% select(team, playoff) %>% rename(playoff_custom = playoff), by = "team" ) %>% mutate(difference = playoff_custom - playoff_default) head(comparison) ``` -------------------------------- ### Configure Parallel Processing with future Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md Set the parallelization strategy using the 'plan' function from the 'future' package. Multisession is recommended for most users. ```r library(future) # Sequential (default, no parallelization) plan(sequential) # Multisession (recommended for most users) plan(multisession) # Multicore (UNIX/Linux/Mac, shares memory) plan(multicore) # Cluster (distributed computing) plan(cluster, workers = c("host1", "host2")) ``` -------------------------------- ### Summarize nflseedR_simulation Results Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/05-types.md This R code demonstrates how to use the summary method on an 'nflseedR_simulation' object. First, it simulates an NFL season using 'simulate_nfl', then it calls 'summary' on the resulting object to display an HTML table of the simulation results. ```r sim <- simulate_nfl(2022, simulations = 100) summary(sim) # Display HTML table ``` -------------------------------- ### Simulate NFL and Display Summary Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md Simulates NFL season outcomes and generates a summary table. Requires the nflseedR package. The summary table displays win averages, playoff probabilities, and more. ```r library(nflseedR) sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 100 ) # Display summary summary(sim) ``` -------------------------------- ### List All Data Dictionaries Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/04-api-schedule.md Lists all available data dictionary objects within the nflseedR package. This is useful for discovering and accessing documentation for different simulation output elements. ```r # Browse all available dictionaries ls(pattern = "^dictionary_") ``` -------------------------------- ### API Reference - Schedule Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/MANIFEST.txt Documentation for the schedule API, including function signatures, parameter details, return values, and error conditions. ```APIDOC ## API Reference - Schedule ### Description Provides access to NFL schedule data. ### Files - 04-api-schedule.md (280 lines, 9.4KB) ### Content - Function signatures - Parameter documentation - Return value documentation - Error conditions - Code examples ``` -------------------------------- ### Compute Draft Order Pipeline Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/02-api-standings.md This snippet demonstrates a full pipeline for computing the NFL draft order. It first computes division ranks, then conference seeds, and finally the draft order itself. The result is then filtered to show the top 5 draft picks. ```r # Full pipeline div_ranks <- compute_division_ranks(games) seeds <- compute_conference_seeds(div_ranks$standings, h2h = div_ranks$h2h) draft <- compute_draft_order(seeds$standings, games = games, h2h = seeds$h2h) draft_top_5 <- draft %>% filter(draft_order <= 5) ``` -------------------------------- ### Run NFL Simulations with Custom Result Function Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md This snippet shows how to use a custom function to compute game results during simulations. Define your own 'my_model' function with the expected signature and pass it to the 'compute_results' parameter. This allows for flexible simulation logic. ```r library(nflseedR) # Custom result function my_model <- function(teams, games, week_num, ...) { # Simulate results based on custom logic list(teams = teams, games = games) } sim <- nfl_simulations( games = nflseedR::sims_games_example, compute_results = my_model, simulations = 100, chunks = 4 ) ``` -------------------------------- ### Custom Win Probability Simulation Model Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Create a custom simulation model that uses provided win probabilities or defaults to a 50-50 split. This model simulates outcomes based on these probabilities and generates a point spread. ```r my_wp_model <- function(teams, games, week_num, wp_source = NULL, ...) { # Use custom win probabilities current <- games %>% filter(week == week_num & is.na(result)) if (nrow(current) == 0) { return(list(teams = teams, games = games)) } # Join win probabilities if (!is.null(wp_source)) { current <- current %>% left_join(wp_source, by = c("sim", "away_team", "home_team")) } else { # Default: 50-50 current <- current %>% mutate(wp_home = 0.5) } # Simulate outcomes current <- current %>% mutate( home_wins = rbinom(n(), 1, wp_home), # Generate point spread from outcome result = ifelse(home_wins == 1, ceiling(abs(rnorm(n(), 5, 10))), -ceiling(abs(rnorm(n(), 5, 10)))) ) games <- games %>% rows_update(current %>% select(sim, game_id, result)) list(teams = teams, games = games) } # Run with custom probabilities sim <- simulate_nfl( nfl_season = 2022, process_games = my_wp_model, wp_source = my_win_probabilities, # Your model output simulations = 500 ) ``` -------------------------------- ### Simulation Modules in R Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/08-implementation-guide.md Overview of the R modules for simulating NFL outcomes, including high-level entry points, low-level controls, and utility functions. ```r # simulate_nfl.R - High-level simulation # `simulate_nfl()` - Main entry point for users # Wraps lower-level functions # Handles built-in ELO model # Orchestrates parallel execution # simulations.R - Low-level simulation # `nfl_simulations()` - Flexible simulation control # Accepts custom result computation function # Handles chunking and aggregation # simulations_utils.R - Simulation utilities # `nflseedR_compute_results()` - Default ELO implementation # Helper functions for simulation logic # simulations_verify_fct.R - Function validation # `simulations_verify_fct()` - Validate custom functions # Checks structure, behavior, and output # simulations_simulate_chunks.R - Parallel chunking # Internal functions for running simulations in parallel # Handles furrr/future integration ``` -------------------------------- ### Data Transformation Pipeline Overview Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/08-implementation-guide.md Visual representation of the data flow through the nflSeedR processing stages, from input data to aggregated statistics. ```text Input Data ↓ [Games Schedule] → Data Validation ↓ [Division Ranking] → Tiebreaker Processing ↓ [Conference Seeding] → Playoff Slot Assignment ↓ [Postseason Simulation] → Optional Playoff Play ↓ [Draft Order] → Optional Draft Ranking ↓ Output: Aggregated Statistics ``` -------------------------------- ### Format Standings Table for Reports Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Customize the simulation results for reports by selecting specific columns, arranging them, and applying formatting using the `gt` package. This allows for professional presentation of simulation data. ```r library(nflseedR) library(gt) library(dplyr) sim <- simulate_nfl(2022, simulations = 1000) # Custom table formatting standings_table <- sim$overall %>% select(team, wins, playoff, seed1, won_sb) %>% arrange(desc(wins)) %>% gt() %>% fmt_number(columns = c(wins, playoff, seed1, won_sb), decimals = 3) %>% tab_header( title = "2022 NFL Season Simulation", subtitle = "1000 Monte Carlo simulations" ) standings_table ``` -------------------------------- ### Enable Global Progress Updates Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md Activates progress reporting globally for all future-based operations. This is useful for long-running simulations where visual feedback is desired. ```r library(progressr) # Global activation (all future-based operations) handlers(global = TRUE) sim <- simulate_nfl(2022, simulations = 1000) # Per-call activation simulate_nfl(2022, simulations = 1000) %>% with_progress() ``` -------------------------------- ### summary.nflseedR_simulation() Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md Generates a formatted HTML summary table from NFL simulation results. This function takes a simulation object and produces an interactive table displaying various probabilities such as playoff, division, conference, and Super Bowl win probabilities. ```APIDOC ## summary.nflseedR_simulation() ### Description Generate a pretty HTML summary table from simulation results. ### Signature ```r summary.nflseedR_simulation(object, ...) ``` ### Parameters #### Parameters - **object** (nflseedR_simulation) - Required - Simulation result from simulate_nfl() or nfl_simulations(). - **...** (—) - Optional - Additional arguments (unused). ### Return Value **Type:** gt table (HTML) An interactive table with team win averages, playoff probability, division win probability, seed probability, conference win probability, and Super Bowl win probability. ### Details Requires gt (>= 0.9.0), scales (>= 1.2.0), and optionally nflplotR (>= 1.2.0) for logos. Table grouped by conference and division with proper formatting and color coding. ### Examples ```r library(nflseedR) sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 100 ) # Display summary summary(sim) ``` ``` -------------------------------- ### simulate_nfl() Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md High-level season simulation function using ELO-based game outcome prediction. ```APIDOC ## simulate_nfl() ### Description High-level season simulation function using ELO-based game outcome prediction. ### Signature ```r simulate_nfl( nfl_season = NULL, process_games = NULL, ..., playoff_seeds = ifelse(nfl_season >= 2020, 7, 6), if_ended_today = FALSE, fresh_season = FALSE, fresh_playoffs = FALSE, tiebreaker_depth = 3, test_week = NULL, simulations = 1000, sims_per_round = max(ceiling(simulations / future::availableCores() * 2), 100), .debug = FALSE, print_summary = FALSE, sim_include = c("DRAFT", "REG", "POST") ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | nfl_season | integer | No | NULL | Season to simulate. If NULL, uses most recent available season. Must be >= 2002. | | process_games | function | No | NULL | Custom function to compute game results. If NULL, uses built-in ELO model. Function signature: process_games(teams, games, week_num, ...). | | playoff_seeds | integer | No | auto | Number of playoff seeds (6 pre-2020, 7 post-2020). | | if_ended_today | logical | No | FALSE | If TRUE, skip remaining games and seed current standings. Simulations becomes 1. | | fresh_season | logical | No | FALSE | If TRUE, clear all regular season results and simulate from scratch. | | fresh_playoffs | logical | No | FALSE | If TRUE, clear all playoff results and simulate from scratch (playoffs only). | | tiebreaker_depth | integer | No | 3 | Depth of tiebreaker application (1-3). See standings documentation. | | test_week | integer | No | NULL | If provided, stop after simulating this week and return process_games output for testing. | | simulations | integer | No | 1000 | Total number of season simulations to run. | | sims_per_round | integer | No | auto | Simulations per parallel round. Auto-calculated based on available cores. Larger values = fewer rounds but more memory. | | .debug | logical | No | FALSE | If TRUE, prints debug information during simulation. | | print_summary | logical | No | FALSE | If TRUE, prints summary statistics after completion. | | sim_include | character | No | "DRAFT" | What to include: "REG" (regular season), "POST" (+ playoffs), "DRAFT" (+ draft order). | | ... | — | No | — | Additional arguments passed to process_games() function. | ### Return Value **Type:** nflseedR_simulation (list) A list containing: - **games:** All simulated game results across all simulations (one row per game per sim) - **standings:** Final standings for each simulation - **overall:** Team-level summary statistics (avg wins, playoff%, div1%, seed1%, etc.) - **team_wins:** Win distribution probabilities per team - **game_summary:** Aggregated game results across simulations - **sim_params:** Input parameters used for simulation ### Throws/Errors | Error | Condition | |-------|-----------| | Invalid season | nfl_season < 2002 or no schedule available | | Invalid process_games | process_games is not a function | | Invalid parameters | Any numeric parameter is not single digit or out of range | ### Details **Built-in ELO Model:** When process_games is NULL, uses a dynamically adjusted ELO rating system: - Initial random ratings drawn from N(1500, 150) - Home field advantage: +20 ELO - Rest advantage: ±(rest_diff / 7) * 25 ELO - Playoff multiplier: 1.2x - K-factor: 20 * multiplier * abs(result) + 1 Game outcome simulated as: home_score - away_score ~ N(elo_diff / 25, 13²) **Parallel Processing:** Supports future-based parallelization. Activate with: ```r future::plan("multisession") # or other plan ``` **Progress Reporting:** Activate with: ```r progressr::handlers(global = TRUE) ``` ### Examples ```r library(nflseedR) library(future) # Simple simulation with defaults sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 100 ) # With parallel processing future::plan("multisession") sim <- simulate_nfl( nfl_season = 2022, simulations = 1000, sims_per_round = 250 ) # Current standings if season ended today current <- simulate_nfl( nfl_season = 2022, if_ended_today = TRUE ) # Custom process_games function custom_model <- function(teams, games, week_num, ...) { # Your custom logic to estimate/simulate games list(teams = teams, games = games) } sim <- simulate_nfl( nfl_season = 2022, process_games = custom_model, simulations = 100 ) ``` ### Source `R/simulate_nfl.R` lines 1-449 ### See Also - `nfl_simulations()` - Low-level simulation with complete control - `nflseedR_compute_results()` - Default result computation function - `summary.nflseedR_simulation()` - Pretty print summary table ``` -------------------------------- ### API Reference - Standings Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/MANIFEST.txt Documentation for the standings API, including function signatures, parameter details, return values, and error conditions. ```APIDOC ## API Reference - Standings ### Description Provides access to NFL standings data. ### Files - 02-api-standings.md (380 lines, 11KB) ### Content - Function signatures - Parameter documentation - Return value documentation - Error conditions - Code examples ``` -------------------------------- ### Set Persistent Parallel Plan Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/06-configuration.md Configure a persistent parallelization plan by adding it to the .Rprofile file. ```r # Add to ~/.Rprofile: # if (!require(future)) install.packages("future") # future::plan("multisession") ``` -------------------------------- ### Season Simulation Functions Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/01-overview.md Functions for simulating NFL seasons, from high-level simulations with default models to low-level simulations with custom result computations. ```APIDOC ## simulate_nfl() ### Description High-level season simulation with default ELO model. ### Method `simulate_nfl()` ### Parameters (Details not provided in source text) ### Request Example (Not provided in source text) ### Response (Details not provided in source text) ``` ```APIDOC ## nfl_simulations() ### Description Low-level simulation with custom result computation. ### Method `nfl_simulations()` ### Parameters (Details not provided in source text) ### Request Example (Not provided in source text) ### Response (Details not provided in source text) ``` -------------------------------- ### View Standings Dictionary Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/04-api-schedule.md Displays the structure of the standings data dictionary. Use this to understand the columns available for standings-related simulation output. ```r library(nflseedR) # View documentation for standings output str(dictionary_standings) ``` -------------------------------- ### nfl_simulations() Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md A low-level simulation function with full control over result computation and playoff configuration. ```APIDOC ## nfl_simulations() ### Description Low-level simulation function with full control over result computation and playoff configuration. ### Signature ```r nfl_simulations( games, compute_results = nflseedR_compute_results, ..., playoff_seeds = 7L, simulations = 10000L, chunks = 8L, byes_per_conf = 1L, tiebreaker_depth = c("SOS", "PRE-SOV", "RANDOM"), sim_include = c("DRAFT", "REG", "POST"), verbosity = c("MIN", "MAX", "NONE") ) ``` ### Parameters #### games - **Type:** data.frame - **Required:** Yes - **Description:** Schedule data with NA results for games to simulate. Must have: sim, game_type, week, away_team, home_team, result. For deep tiebreakers, include home_score, away_score. #### compute_results - **Type:** function - **Required:** No - **Default:** nflseedR_compute_results - **Description:** Function to compute game results. Signature: compute_results(teams, games, week_num, ...). #### playoff_seeds - **Type:** integer - **Required:** No - **Default:** 7L - **Description:** Number of playoff seeds (6-7). Ignored if byes_per_conf differs from modern standard. #### simulations - **Type:** integer - **Required:** No - **Default:** 10000L - **Description:** Total simulations to run. #### chunks - **Type:** integer - **Required:** No - **Default:** 8L - **Description:** Number of parallel chunks. Each chunk processes simulations / chunks simulations. #### byes_per_conf - **Type:** integer - **Required:** No - **Default:** 1L - **Description:** Number of bye weeks per conference (affects playoff bracket structure). #### tiebreaker_depth - **Type:** character - **Required:** No - **Default:** "SOS" - **Description:** Tiebreaker depth: "RANDOM", "PRE-SOV", "SOS". #### sim_include - **Type:** character - **Required:** No - **Default:** "DRAFT" - **Description:** What to include: "REG", "POST", "DRAFT". #### verbosity - **Type:** character - **Required:** No - **Default:** "MIN" - **Description:** Reporting level: "NONE", "MIN", "MAX". #### ... - **Type:** — - **Required:** No - **Description:** Additional arguments passed to compute_results() function. ### Return Value **Type:** nflseedR_simulation (list) Same structure as simulate_nfl(): - **games:** All simulated games - **standings:** Final standings per simulation - **overall:** Aggregated team statistics - **team_wins:** Win probability distributions - **game_summary:** Aggregated game outcomes - **sim_params:** Input parameters ### Details The `compute_results` function is called once per simulated week with: - **teams:** Team roster with ratings/state (mutable between weeks) - **games:** Full schedule with results filled progressively - **week_num:** Current week being simulated (factor: "1"-"18", "WC", "DIV", "CON", "SB") The function must: 1. Return a list with "teams" and "games" elements 2. Only modify results where week == week_num && is.na(result) 3. Not remove rows/columns 4. Ensure playoff games never end in ties Reproducible RNG requires: ```r set.seed(123, kind = "L'Ecuyer-CMRG") ``` ### Examples ```r library(nflseedR) # Using default ELO computation sim <- nfl_simulations( games = nflseedR::sims_games_example, simulations = 1000, chunks = 10 ) # Custom result function my_model <- function(teams, games, week_num, ...) { # Simulate results based on custom logic list(teams = teams, games = games) } sim <- nfl_simulations( games = nflseedR::sims_games_example, compute_results = my_model, simulations = 100, chunks = 4 ) # Verify custom function before running simulations_verify_fct(my_model) ``` ### Source `R/simulations.R` ### See Also - `nflseedR_compute_results()` - Default implementation - `simulations_verify_fct()` - Validate custom function - `summary.nflseedR_simulation()` - Generate summary table ``` -------------------------------- ### Compute Matchups from Previous Season Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/09-usage-patterns.md Load schedules and standings from a previous season to compute the matchups for the next season. This involves grouping and summarizing opponent types. ```r library(nflseedR) library(dplyr) # Get 2022 final standings games_2022 <- nflreadr::load_schedules(2022) standings_2022 <- nfl_standings(games_2022, ranks = "DIV") # Compute 2023 matchups matchups_2023 <- nfl_regular_season(standings_2022) # Count opponent types matchups_2023 %>% group_by(team, opp_type) %>% summarize(count = n()) ``` -------------------------------- ### Data Objects Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/01-overview.md Key data objects available within the nflseedR package for reference and use in simulations. ```APIDOC ## divisions ### Description Team/conference/division mapping. ### Type Data object (e.g., data frame, tibble) ### Content (Details not provided in source text) ``` ```APIDOC ## sims_games_example ### Description Example schedule for demonstrations. ### Type Data object (e.g., data frame, tibble) ### Content (Details not provided in source text) ``` ```APIDOC ## sims_teams_example ### Description Example team data for demonstrations. ### Type Data object (e.g., data frame, tibble) ### Content (Details not provided in source text) ``` ```APIDOC ## dictionary_* ### Description Data structure documentation. ### Type Data object (documentation) ### Content (Details not provided in source text) ``` -------------------------------- ### Verify Built-in nflseedR Function Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md Use this to check the default `nflseedR_compute_results` function against nflseedR requirements. It should return TRUE if all checks pass. ```r library(nflseedR) # Check the built-in function simulations_verify_fct(nflseedR::nflseedR_compute_results) # Returns TRUE ``` -------------------------------- ### Simple NFL Season Simulation Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/03-api-simulation.md Performs a basic simulation of the 2022 NFL season with default settings, ensuring a fresh season simulation. Requires the nflseedR and future libraries. ```r library(nflseedR) library(future) # Simple simulation with defaults sim <- simulate_nfl( nfl_season = 2022, fresh_season = TRUE, simulations = 100 ) ``` -------------------------------- ### nfl_standings() Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/02-api-standings.md Computes complete NFL standings including division ranks, conference seeds, and optionally draft order, with configurable tiebreaker depth. ```APIDOC ## nfl_standings() ### Description Compute complete NFL standings including division ranks, conference seeds, and optionally draft order, with configurable tiebreaker depth. ### Signature ```r nfl_standings( games, ..., ranks = c("CONF", "DIV", "DRAFT", "NONE"), tiebreaker_depth = c("SOS", "PRE-SOV", "POINTS", "RANDOM"), playoff_seeds = NULL, verbosity = c("MIN", "MAX", "NONE") ) ``` ### Parameters #### Path Parameters - **games** (data.frame) - Required - Schedule data with game results. Must contain: sim (or season), game_type, week, away_team, home_team, result. For tiebreakers beyond SOS, must also include home_score and away_score. - **ranks** (character) - Optional - Type of ranking to compute. "NONE" returns raw standings, "DIV" includes division ranks, "CONF" adds conference ranks, "DRAFT" adds draft order. Default: "CONF" - **tiebreaker_depth** (character) - Optional - Which tiebreakers to apply. "RANDOM" breaks all ties by coin flip, "PRE-SOV" applies through Strength of Victory, "SOS" applies through Strength of Schedule (deepest), "POINTS" applies through point differential. Default: "SOS" - **playoff_seeds** (integer) - Optional - Number of conference seeds to compute (1-16). If NULL, computes all 16. Lower values improve performance by skipping deep tiebreakers for non-playoff spots. Default: NULL - **verbosity** (character) - Optional - Reporting level. "NONE" suppresses output, "MIN" shows main steps, "MAX" shows detailed tiebreaker activity. Default: "MIN" - **...** (—) - Optional - Currently unused, reserved for future parameters. ### Return Value **Type:** data.table (tibble) A standings table with one row per team per simulation containing: - **Core fields:** sim, conf, division, team, games, wins, losses, ties, win_pct - **If ranks includes "DIV":** div_rank (1-4, division winner is 1) - **If ranks includes "CONF":** conf_rank or seed (1-7 for modern era, 1-6 pre-2020), exit (week team eliminated) - **If ranks = "DRAFT":** draft_order (1-32, #1 is worst team) ### Throws/Errors - **Invalid ranks**: ranks not in allowed values - **Invalid tiebreaker_depth**: tiebreaker_depth not in allowed values - **playoff_seeds out of range**: playoff_seeds < 1 or > 16 - **Missing required columns**: games lacks sim/season, game_type, week, away_team, home_team, or result - **Missing scores for deep tiebreakers**: tiebreaker_depth="POINTS" but home_score/away_score missing ### Details The function implements the complete NFL tiebreaker hierarchy: 1. Head-to-head record (within division/conference as applicable) 2. Division win percentage (division rankings only) 3. Common games win percentage 4. Strength of Victory (wins against teams ≥ 0.500) 5. Strength of Schedule (combined opponent record) 6. Point differential (if enabled) 7. Random (coin flip) For division rankings, tiebreakers apply within each division. For conference rankings, tiebreakers apply within groups of teams with same division rank. ### Examples ```r library(nflseedR) # Load actual schedule and compute current standings games <- nflreadr::load_schedules(2022) standings <- nfl_standings(games, ranks = "CONF") head(standings) # Compute standings with minimal tiebreakers for speed standings_fast <- nfl_standings( games, ranks = "DIV", tiebreaker_depth = "RANDOM" ) # Compute draft order (requires complete season) draft <- nfl_standings( games, ranks = "DRAFT", tiebreaker_depth = "SOS", playoff_seeds = 7 ) # Suppress status messages standings_quiet <- nfl_standings( games, ranks = "CONF", verbosity = "NONE" ) ``` ``` -------------------------------- ### Validate Data Before Running Functions Source: https://github.com/nflverse/nflseedr/blob/master/_autodocs/07-errors.md Implement checks to ensure required data columns exist and that custom functions are valid before proceeding. This prevents unexpected errors later in the workflow. It also includes a check to load schedule data if it doesn't exist, with error handling for the loading process. ```r # Validate games data games <- nflreadr::load_schedules(2022) required_cols <- c("season", "game_type", "week", "away_team", "home_team", "result") if (!all(required_cols %in% names(games))) { missing <- setdiff(required_cols, names(games)) stop("Missing columns: ", paste(missing, collapse = ", ")) } # Verify custom function simulations_verify_fct(my_custom_function) # Check season validity if (!exists("games")) { games <- try(nflreadr::load_schedules(2022)) if (inherits(games, "try-error")) { message("Could not load schedule") } } ```