### Install cricketdata from GitHub Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Installs the development version of the cricketdata package directly from GitHub. Requires the devtools package to be installed first. ```r install.packages("devtools") devtools::install_github("robjhyndman/cricketdata") ``` -------------------------------- ### Example: Download Meta Data for Multiple Players Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_meta.html This example demonstrates how to download meta data for multiple players by passing a vector of their Cricinfo player IDs to the `fetch_player_meta` function. The results are stored in the `aus_women` tibble. ```R if (FALSE) { # \dontrun{ # Download meta data on Meg Lanning and Ellyse Perry aus_women <- fetch_player_meta(c(329336, 275487)) } # } ``` -------------------------------- ### Install cricketdata from CRAN Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Installs the stable version of the cricketdata package from CRAN. Ensure dependencies are installed for full functionality. ```r install.packages("cricketdata", dependencies = TRUE) ``` -------------------------------- ### Install Development Version of cricketdata Source: https://pkg.robjhyndman.com/cricketdata/index.html Install the development version of the cricketdata package from Github using the pak package manager. ```r pak::pak("robjhyndman/cricketdata") ``` -------------------------------- ### Example: Fetching WBBL Data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_cricsheet.html Demonstrates how to fetch ball-by-ball, match, and player data for the WBBL competition. This code is for demonstration and will not run unless the condition is met. ```R if (FALSE) { # \dontrun{ wbbl_bbb <- fetch_cricsheet(competition = "wbbl", type = "bbb") wbbl_match <- fetch_cricsheet(competition = "wbbl", type = "match") wbbl_player <- fetch_cricsheet(competition = "wbbl", type = "player") } # } ``` -------------------------------- ### Load cricketdata, dplyr, and ggplot2 Libraries Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Loads the necessary R libraries for data manipulation and visualization. Ensure these packages are installed before running. ```r library(cricketdata) library(dplyr) library(ggplot2) ``` -------------------------------- ### Examples of Fetching Cricinfo Data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_cricinfo.html Demonstrates how to use the `fetch_cricinfo` function to retrieve specific datasets, such as women's T20 data for Australia and men's ODI bowling data for India. ```R if (FALSE) { # \dontrun{ auswt20 <- fetch_cricinfo("T20", "Women", country = "Aust") IndiaODIBowling <- fetch_cricinfo("ODI", "men", "bowling", country = "india") } # } ``` -------------------------------- ### Install Stable Version of cricketdata Source: https://pkg.robjhyndman.com/cricketdata/index.html Install the stable version of the cricketdata package from CRAN using the pak package manager. ```r # install.packages("pak") pak::pak("cricketdata") ``` -------------------------------- ### Load cricketdata and Libraries Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Loads necessary R libraries for data manipulation, visualization, and fetching Cricsheet data. Ensure these packages are installed before running. ```r library(cricketdata) library(readr) library(dplyr) #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union library(stringr) library(showtext) #> Loading required package: sysfonts #> Loading required package: showtextdb library(ggplot2) library(gghighlight) library(ggtext) library(patchwork) ``` -------------------------------- ### Fetch Cricsheet Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Fetches data from Cricsheet by specifying the type (ball-by-ball, match, player), gender, and competition. Example shown for WBBL female data. ```r # Fetch ball-by-ball data wbbl_bbb <- fetch_cricsheet(competition = "wbbl", gender = "female") # Fetch match metadata wbbl_match_info <- fetch_cricsheet(competition = "wbbl", type = "match", gender = "female") ``` -------------------------------- ### Find Player ID using Name Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Use `find_player_id` to get a player's Cricinfo ID from their name. This ID is essential for fetching individual player data. ```R # Fetching a player, Meg Lanning's, ID meg_lanning_id <- find_player_id("Meg Lanning")$ID ``` ```R meg_lanning_id #> [1] 329336 ``` -------------------------------- ### fetch_player_meta Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Fetches player meta data. ```APIDOC ## fetch_player_meta() ### Description Fetch Player Meta Data. ### Usage fetch_player_meta() ### Details This function retrieves metadata associated with players. ``` -------------------------------- ### fetch_player_data Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Fetches player data. ```APIDOC ## fetch_player_data() ### Description Fetch Player Data. ### Usage fetch_player_data() ### Details This function is used to retrieve player-specific data. ``` -------------------------------- ### Fetch Player Metadata by ID Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Fetches meta data for specified player IDs using the fetch_player_meta() function. This is useful for obtaining detailed information on individual players for advanced modeling. ```r # Download meta data on Meg Lanning and Ellyse Perry aus_women <- fetch_player_meta(c(329336, 275487)) ``` ```r aus_women |> select(-name) |> knitr::kable( digits = 1, align = "c", format = "pipe", col.names = c( "ID", "FullName", "Country", "DOB", "BattingStyle", "BowlingStyle" ) ) ``` -------------------------------- ### Download and Plot Player Data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_data.html Demonstrates downloading player data for different match types and activities, and then plotting T20 batting scores using dplyr and ggplot2. ```R if (FALSE) { # \dontrun{ # Download data on some players EllysePerry <- fetch_player_data(275487, "T20", "batting") RahulDravid <- fetch_player_data(28114, "ODI", "fielding") LasithMalinga <- fetch_player_data(49758, "Test", "bowling") # Create a plot for Ellyse Perry's T20 scores library(dplyr) library(ggplot2) EllysePerry |> filter(!is.na(Runs)) |> ggplot(aes(x = Start_Date, y = Runs, col = Dismissal, na.rm = TRUE)) + geom_point() + ggtitle("Ellyse Perry's T20 Scores") } # } ``` -------------------------------- ### update_player_meta Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Updates player_meta. ```APIDOC ## update_player_meta() ### Description Update player_meta. ### Usage update_player_meta() ### Details This function is used to update the player_meta data. ``` -------------------------------- ### Display Player Metadata Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Filters and selects specific columns from the player_meta dataset, then formats the output for display using knitr::kable. Use this to view a subset of player information. ```r player_meta |> filter(!is.na(playing_role)) |> select(-cricinfo_id, -unique_name, -name) |> head() |> knitr::kable( digits = 1, align = "c", format = "pipe", col.names = c( "ID", "FullName", "Country", "DOB", "BirthPlace", "BattingStyle", "BowlingStyle", "PlayingRole" ) ) ``` -------------------------------- ### fetch_player_meta() Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Fetches player meta data such as full name, country of representation, date of birth, bowling and batting hand, bowling style, and playing role. This data is useful for advanced modeling. ```APIDOC ## fetch_player_meta() ### Description Fetch the player’s meta data such as full name, country of representation, data of birth, bowling and batting hand, bowling style, and playing role. This meta data is useful for advance modeling, e.g, age curves, batter profile against bowling types etc. ### Arguments * `playerid`: A vector of player IDs as given in Cricinfo profiles. Integer or character. ### Example ```R # Download meta data on Meg Lanning and Ellyse Perry aus_women <- fetch_player_meta(c(329336, 275487)) aus_women |> select(-name) |> knitr::kable( digits = 1, align = "c", format = "pipe", col.names = c( "ID", "FullName", "Country", "DOB", "BattingStyle", "BowlingStyle" ) ) ``` ``` -------------------------------- ### Fetch Player Data Function Signature Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_data.html Defines the parameters for fetching player data, including player ID, match type, and activity. ```R fetch_player_data( playerid, matchtype = c("test", "odi", "t20"), activity = c("batting", "bowling", "fielding") ) ``` -------------------------------- ### Update Player Meta Data Source: https://pkg.robjhyndman.com/cricketdata/reference/update_player_meta.html Fetches the latest player meta data. Optionally, it can re-download all data from ESPNCricinfo if `start_again` is set to TRUE. ```APIDOC ## update_player_meta ### Description Updates the player_meta data set with current information available online. ### Usage ```R update_player_meta(start_again = FALSE) ``` ### Arguments * `start_again` (logical) - If TRUE, downloads all data from ESPNCricinfo without using player_meta as a starting point. This can take a long time. ### Value A tibble containing meta data on cricket players. ### Examples ```R # Update data to current new_player_meta <- update_player_meta() ``` ``` -------------------------------- ### Fetch Indian Test Fielding Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Retrieves fielding statistics for Indian Men in Test matches. This data can be used to analyze player performance in the field. ```r Indfielding <- fetch_cricinfo("Test", "Men", "Fielding", country = "India") ``` -------------------------------- ### Load Google Fonts for Plotting Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Imports 'Roboto Condensed' and 'Staatliches' fonts from Google Fonts for use in plots. Ensures automatic display of loaded fonts. ```r # Import fonts from Google Fonts font_add_google("Roboto Condensed", "roboto_con") font_add_google("Staatliches", "staat") showtext_auto() ``` -------------------------------- ### Fetch IPL Ball-by-Ball Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Fetches all ball-by-ball data for the Indian Premier League (IPL). The fetched data can be inspected using glimpse(). ```R ipl_bbb <- fetch_cricsheet("bbb", "male", "ipl") ipl_bbb |> glimpse() ``` -------------------------------- ### Fetch Meg Lanning's ODI Batting Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Fetches ODI batting data for a specific player, Meg Lanning, by first finding her player ID. It also adds a 'NotOut' column. ```r meg_lanning_id <- find_player_id("Meg Lanning")$ID MegLanning <- fetch_player_data(meg_lanning_id, "ODI") |> mutate(NotOut = (Dismissal == "not out")) |> mutate(NotOut = tidyr::replace_na(NotOut, FALSE)) ``` -------------------------------- ### Display and Summarize Women's T20 Bowling Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Displays a glimpse of the fetched T20 bowling data for women and then creates a formatted table of key career statistics. This is useful for a quick overview of player performance. ```R # Looking at data wt20 |> glimpse() #> Rows: 2,753 #> Columns: 16 #> $ Player "M Schutt", "Nida Dar", "DB Sharma", "S Ecclestone"… #> $ Country "Australia", "Pakistan", "India", "England", "THA",… #> $ Start 2013, 2010, 2016, 2016, 2018, 2008, 2008, 2007, 200… #> $ End 2025, 2024, 2024, 2025, 2025, 2025, 2021, 2023, 202… #> $ Matches 122, 160, 124, 96, 99, 167, 117, 113, 145, 98, 112,… #> $ Innings 121, 152, 121, 95, 98, 137, 113, 112, 122, 93, 111,… #> $ Overs 413.1, 510.2, 436.5, 355.2, 331.4, 407.5, 395.3, 39… #> $ Maidens 10, 13, 12, 10, 23, 8, 6, 21, 6, 21, 17, 30, 4, 13,… #> $ Runs 2632, 2910, 2642, 2089, 1363, 2385, 2206, 2291, 227… #> $ Wickets 149, 144, 138, 137, 126, 126, 125, 123, 118, 116, 1… #> $ Average 17.664430, 20.208333, 19.144928, 15.248175, 10.8174… #> $ Economy 6.370311, 5.702155, 6.048073, 5.878987, 4.109548, 5… #> $ StrikeRate 16.63758, 21.26389, 18.99275, 15.56204, 15.79365, 1… #> $ BestBowlingInnings "5/15", "5/21", "4/10", "4/18", "5/5", "4/12", "5/1… #> $ FourWickets 4, 1, 1, 2, 5, 4, 4, 0, 1, 6, 1, 2, 4, 1, 3, 2, 3, … #> $ FiveWickets 1, 1, 0, 0, 1, 0, 3, 2, 0, 2, 0, 0, 0, 2, 3, 1, 0, … # Table showing certain features of the data wt20 |> select(Player, Country, Matches, Runs, Wickets, Economy, StrikeRate) |> head() |> knitr::kable( digits = 2, align = "c", caption = "Women Player career profile for international T20" ) ``` -------------------------------- ### fetch_cricsheet Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Fetches ball-by-ball, match, and player data from Cricsheet. ```APIDOC ## fetch_cricsheet() ### Description Fetch ball-by-ball, match and player data from Cricsheet and return a tibble. ### Usage fetch_cricsheet() ### Details This function retrieves various types of data from Cricsheet, including ball-by-ball, match, and player information, and returns it as a tibble. ``` -------------------------------- ### Plotting Batting Average per Season with gghighlight Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Generates a line plot showing average runs per innings for each season, highlighting specific players. Requires ggplot2 and gghighlight libraries. Customizes theme and text elements for presentation. ```r batting_per_season |> ggplot(aes( x = season, y = runs_per_innings_avg, group = striker, colour = is_healy )) + geom_line(linewidth = 2, colour = "#F80F61FF") + gghighlight(is_healy, label_key = striker, label_params = aes( size = 6, force_pull = 0.1, nudge_y = 10, label.size = 1, family = "roboto_con", label.padding = 0.5, fill = "#19232FFF", colour = "#F80F61FF" ), unhighlighted_params = list(size = 1, color = "#187999FF") ) + labs( title = "WBBL: Average runs scored per innings (3+ innings)", x = NULL, y = NULL, caption = "**Source:** Cricsheet.org // **Plot:** @jacquietran" ) + theme_minimal() + theme( text = element_text(size = 18, family = "roboto_con", colour = "#FFFFFF"), plot.title = element_text(family = "staat", margin = margin(0, 0, 15, 0)), plot.caption = element_markdown(size = NULL, margin = margin(15, 0, 0, 0)), axis.text = element_text(colour = "#FFFFFF"), legend.position = "none", panel.grid.major = element_line(linetype = "dashed"), panel.grid.minor = element_blank(), plot.background = element_rect( fill = "#171F2AFF", colour = NA ), panel.spacing = unit(2, "lines"), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm") ) ``` -------------------------------- ### Access Player Meta Data Source: https://pkg.robjhyndman.com/cricketdata/reference/player_meta.html Load and view the player_meta dataset. This dataset contains player names and attributes from ESPNCricinfo. ```r player_meta ``` -------------------------------- ### Subset WBBL07 Match Metadata in R Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Filters and selects specific columns from the `wbbl_match_info` dataset to create a tidy subset for WBBL07 games played up to a certain date. Ensures `match_id` is a factor for consistent analysis. ```r # Subset match metadata for WBB07 games wbbl07_match_info_tidy <- wbbl_match_info |> filter(season == "2021/22", date <= "2021/11/07") |> select( match_id, winner, winner_runs, winner_wickets, method, outcome, eliminator ) |> mutate(match_id = factor(match_id)) ``` -------------------------------- ### fetch_cricinfo Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Fetches data from Cricinfo. ```APIDOC ## fetch_cricinfo() ### Description Fetch Data from Cricinfo. ### Usage fetch_cricinfo() ### Details This function is used to retrieve data from the Cricinfo website. ``` -------------------------------- ### Filter Dismissals by Striker (R) Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Filters the dismissals_by_ball_number_summary dataset to include only dismissals for a specific striker. Useful for isolating player-specific statistics. ```r dismissals_by_ball_number_summary_devine <- dismissals_by_ball_number_summary |> filter(striker == "SFM Devine") ``` ```r dismissals_by_ball_number_summary_knight <- dismissals_by_ball_number_summary |> filter(striker == "HC Knight") ``` -------------------------------- ### Fetch Player Meta Data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_meta.html Fetches meta data for specified players using their Cricinfo player IDs. ```APIDOC ## Fetch Player Meta Data ### Description Fetches player meta data from ESPNCricinfo and returns a tibble with one line per player. To identify the players, use their Cricinfo player IDs. The simplest way to find this is to look up their Cricinfo Profile page. The number at the end of the URL is the ID. For example, Meg Lanning's profile page is https://www.espncricinfo.com/cricketers/meg-lanning-329336, so her ID is 329336. ### Usage ```R fetch_player_meta(playerid) ``` ### Arguments * **playerid** (Integer or character vector) - A vector of player IDs as given in Cricinfo profiles. ### Value A tibble containing meta data on the selected players, with one row for each player. ### Examples ```R # Download meta data on Meg Lanning and Ellyse Perry aus_women <- fetch_player_meta(c(329336, 275487)) ``` ``` -------------------------------- ### Generate Table of Top IPL 2022 Batters Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Generates a formatted table summarizing the top 10 batters in the IPL 2022 season, including their total runs, balls faced, strike rate, dot percentage, and boundary percentage. This provides a concise overview of high-performing players. ```R ipl_bbb |> filter(season == "2022") |> group_by(striker) |> summarize( Runs = sum(runs_off_bat), BallsFaced = n() - sum(!is.na(wides)), StrikeRate = Runs / BallsFaced, DotPercent = sum(runs_off_bat == 0) * 100 / BallsFaced, BoundaryPercent = sum(runs_off_bat %in% c(4, 6)) * 100 / BallsFaced ) |> arrange(desc(Runs)) | rename(Batter = striker) | slice(1:10) |> knitr::kable(digits = 1, align = "c") ``` -------------------------------- ### Fetch Cricsheet Ball-by-Ball Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Download ball-by-ball data from Cricsheet. Specify the data type, gender, and competition. The raw T20 data is further processed to add analytical features. ```R # Indian Premier League (IPL) Ball-by-Ball Data # fetch_cricsheet(type = "bbb", gender = "male", competition = "ipl") ``` -------------------------------- ### update_player_meta() Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html This function consults the directory of all players available on the cricsheet website and includes the meta data of new players into the `player_meta` data frame. Data for new players is scraped from ESPNCricinfo. ```APIDOC ## update_player_meta() ### Description This function is supposed to consult the directory of all players available on cricsheet website and include the meta data of new players into the `player_meta` data frame. The data for new players will be scraped from the ESPNCricinfo. ``` -------------------------------- ### Fetch Australian Men's ODI Data by Innings Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Fetches Australian Men's ODI batting data, with each row representing an innings. Specify format and country. ```r # Fetch all Australian Men's ODI data by innings menODI <- fetch_cricinfo("ODI", "Men", "Batting", type = "innings", country = "Australia") ``` -------------------------------- ### Fetch Player Meta Data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_meta.html Use this function to download meta data for specific players from ESPNCricinfo. Requires player IDs, which can be found in the URL of their Cricinfo profile pages. The function returns a tibble with one row per player. ```R fetch_player_meta(playerid) ``` -------------------------------- ### Load cricketdata and dplyr Libraries Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Loads the necessary cricketdata and dplyr libraries for data manipulation and analysis. dplyr is commonly used for data wrangling tasks. ```r library(cricketdata) library(dplyr) #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union library(ggplot2) ``` -------------------------------- ### Update Player Meta Data Source: https://pkg.robjhyndman.com/cricketdata/reference/update_player_meta.html Call this function to update the player meta data to the most current version available online. The function returns a tibble with player meta information. ```R new_player_meta <- update_player_meta() ``` -------------------------------- ### Fetch USA Men's ODI Batting Data by Innings Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Fetches innings-by-innings batting data for male players representing the USA in One Day Internationals. This is useful for detailed analysis of individual performances in specific matches. ```R # Fetch all USA Men's ODI data by innings menODI <- fetch_cricinfo("ODI", "Men", "Batting", type = "innings", country = "United States of America" ) ``` -------------------------------- ### Build Cricket Dismissals Plot (R) Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Generates a ggplot2 boxplot showing the percentage of dismissals by ball number for a specific player. Uses geom_boxplot for distribution and geom_point for individual player data. ```r showtext_auto() # Healy p1 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_healy, colour = "#F80F61FF", size = 3 ) + labs( title = "WBBL: % dismissals by ball number", subtitle = "AJ Healy" ) + plot_features ``` ```r # Mooney p2 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_mooney, colour = "#FA6900FF", size = 3 ) + labs(subtitle = "BL Mooney") + plot_features ``` ```r # Lanning p3 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_lanning, colour = "#018821FF", size = 3 ) + labs(subtitle = "MM Lanning") + plot_features ``` ```r # Perry p4 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_perry, colour = "#F80F61FF", size = 3 ) + labs(subtitle = "EA Perry") + plot_features ``` ```r # Devine p5 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_devine, colour = "#FA6900FF", size = 3 ) + labs(subtitle = "SFM Devine") + plot_features ``` ```r # Knight p6 <- dismissals_by_ball_number_summary |> ggplot(aes(x = ball_num_in_over, y = dismissals_pct)) + geom_boxplot( fill = "#FFFFFF", colour = "#FFFFFF", size = .5, alpha = 0.25, notch = TRUE, outlier.shape = NA, coef = 0 ) + geom_point( data = dismissals_by_ball_number_summary_knight, colour = "#95C65CFF", size = 3 ) + labs( subtitle = "HC Knight", caption = "**Source:** Cricsheet.org // **Plot:** @jacquietran" ) + plot_features ``` -------------------------------- ### Calculating League-Wide Dismissal Rate by Ball Number Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Merges ball-facing and dismissal data to calculate the league-wide dismissal rate per ball number. Filters for batters facing over 200 balls and excludes balls beyond the 6th. Also extracts data for specific players. ```r # Merge data and summarise to league-wide dismissals rate by ball number dismissals_by_ball_number_summary <- left_join( ball_number_faced_summary, dismissals_by_ball_number, by = c("ball_num_in_over", "striker") ) |> tidyr::replace_na(list(dismissals_n = 0)) |> group_by(striker) | mutate(total_balls_faced = sum(balls_faced)) | ungroup() | mutate(dismissals_pct = round(dismissals_n / balls_faced * 100, 2)) | # Include those who have faced more than 200 balls total filter(total_balls_faced >= 200) | # Exclude balls beyond 6 - infrequent occurrences filter(ball_num_in_over < 7) # Extract data for specific players # Healy dismissals_by_ball_number_summary_healy <- dismissals_by_ball_number_summary | filter(striker == "AJ Healy") # Mooney dismissals_by_ball_number_summary_mooney <- dismissals_by_ball_number_summary | filter(striker == "BL Mooney") # Lanning dismissals_by_ball_number_summary_lanning <- dismissals_by_ball_number_summary | filter(striker == "MM Lanning") # Perry dismissals_by_ball_number_summary_perry <- dismissals_by_ball_number_summary | filter(striker == "EA Perry") ``` -------------------------------- ### player_meta Source: https://pkg.robjhyndman.com/cricketdata/reference/index.html Provides meta data on players listed at ESPNCricinfo. ```APIDOC ## player_meta ### Description Meta data on players listed at ESPNCricinfo. ### Details This object contains metadata for players found on ESPNCricinfo. ``` -------------------------------- ### Visualize Indian Men Test Fielding Performance Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Creates a scatter plot comparing the number of matches played against dismissals for Indian Men in Test cricket, differentiating wicketkeepers. Requires dplyr and ggplot2. ```r Indfielding |> mutate(wktkeeper = (CaughtBehind > 0) | (Stumped > 0)) |> ggplot(aes(x = Matches, y = Dismissals, col = wktkeeper)) + geom_point() + ggtitle("Indian Men Test Fielding") ``` -------------------------------- ### fetch_cricinfo Function Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_cricinfo.html Fetches data from ESPNCricinfo and returns it as a tibble. All arguments are case-insensitive and partially matched. ```APIDOC ## fetch_cricinfo ### Description Fetches data from ESPNCricinfo and return a tibble. All arguments are case-insensitive and partially matched. ### Usage ```R fetch_cricinfo( matchtype = c("test", "odi", "t20"), sex = c("men", "women"), activity = c("batting", "bowling", "fielding"), type = c("career", "innings"), country = NULL ) ``` ### Arguments * **matchtype** (Character) - Indicates test (default), odi, or t20. * **sex** (Character) - Indicates men (default) or women. * **activity** (Character) - Indicates batting (default), bowling or fielding. * **type** (Character) - Indicates innings-by-innings or career (default) data. * **country** (Character, Optional) - Indicates country. The default is to fetch data for all countries. ### Value A `tibble` object, similar to a `data.frame`. ### Examples ```R # Fetch T20 data for women in Australia auswt20 <- fetch_cricinfo("T20", "Women", country = "Aust") # Fetch ODI bowling data for men in India IndiaODIBowling <- fetch_cricinfo("ODI", "men", "bowling", country = "india") ``` ``` -------------------------------- ### Fetch Cricsheet Data Function Signature Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_cricsheet.html Defines the arguments for fetching data: type (bbb, match, player), gender (female, male), and competition code. ```R fetch_cricsheet( type = c("bbb", "match", "player"), gender = c("female", "male"), competition = "tests" ) ``` -------------------------------- ### Fetch Women's T20 Bowling Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Fetches all available Women's T20 bowling data from ESPNCricinfo. Respect ESPNCricinfo's terms of use. ```r # Fetch all Women's T20 data wt20 <- fetch_cricinfo("T20", "Women", "Bowling") ``` -------------------------------- ### player_meta Dataset Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html A dataset containing player’s and cricket officials meta data such as full name, country of representation, date of birth, bowling and batting hand, bowling style, and playing role. Over 11,000 player’s and officials data is available, scraped from the ESPNCricinfo website. ```APIDOC ## player_meta ### Description It is a data set containing player’s and cricket officials meta data such as full name, country of representation, data of birth, bowling and batting hand, bowling style, and playing role. More than 11,000 player’s and officials data is available. This data was scraped from ESPNCricinfo website. ### Example ```R player_meta |> filter(!is.na(playing_role)) |> select(-cricinfo_id, -unique_name, -name) |> head() |> knitr::kable( digits = 1, align = "c", format = "pipe", col.names = c( "ID", "FullName", "Country", "DOB", "BirthPlace", "BattingStyle", "BowlingStyle", "PlayingRole" ) ) ``` ``` -------------------------------- ### Analyze IPL 2022 Batters Boundary and Dot Percentage Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Calculates and visualizes the boundary and dot ball percentages for top batters in the IPL 2022 season. This plot helps identify players with high boundary-hitting ability and low dot ball frequency. ```R ipl_bbb |> filter(season == "2022") |> group_by(striker) |> summarize( Runs = sum(runs_off_bat), BallsFaced = n() - sum(!is.na(wides)), StrikeRate = Runs / BallsFaced, DotPercent = sum(runs_off_bat == 0) * 100 / BallsFaced, BoundaryPercent = sum(runs_off_bat %in% c(4, 6)) * 100 / BallsFaced ) |> arrange(desc(Runs)) |> rename(Batter = striker) |> slice(1:20) |> ggplot(aes(y = BoundaryPercent, x = DotPercent, size = BallsFaced)) + geom_point(color = "red", alpha = 0.3) + geom_text(aes(label = Batter), vjust = -0.5, hjust = 0.5, color = "#013369", position = position_dodge(0.9), size = 3 ) + ylab("Boundary Percent") + xlab("Dot Percent") + ggtitle("IPL 2022: Top 20 Batters") ``` -------------------------------- ### Compute Meg Lanning's Batting Average Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Calculates Meg Lanning's batting average from her ODI data, excluding innings where she was not out. Requires dplyr. ```r # Compute batting average MLave <- MegLanning |> summarise( Innings = sum(!is.na(Runs)), Average = sum(Runs, na.rm = TRUE) / (Innings - sum(NotOut, na.rm=TRUE)) ) |> pull(Average) names(MLave) <- paste("Average =", round(MLave, 2)) ``` -------------------------------- ### Tidying Ball-by-Ball Cricket Data Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Prepares ball-by-ball cricket data to calculate the number of balls faced and dismissals for each ball number within an over. Filters out specific seasons and ball numbers, and applies a minimum balls faced threshold. ```r # Create new variable for ball number in each over ball_number_faced <- wbbl_bbb_tidy | mutate(ball_num_in_over = sub(".*\\.", "", ball)) # Summarise number of balls faced of each ball number, per batter ball_number_faced_summary <- ball_number_faced | group_by(ball_num_in_over, striker) | summarise(balls_faced = n(), .groups = "drop") # Dismissals by ball number dismissals_by_ball_number <- ball_number_faced | select(ball_num_in_over, striker, wicket_type) | filter(wicket_type != "") | group_by(ball_num_in_over, striker) | summarise(dismissals_n = n(), .groups = "drop") ``` -------------------------------- ### Access Cricsheet Codes Data Frame Source: https://pkg.robjhyndman.com/cricketdata/reference/cricsheet_codes.html This snippet shows how to access the `cricsheet_codes` data frame, which contains competition names and codes used by Cricsheet. No specific imports are required as it's a built-in dataset. ```R cricsheet_codes ``` -------------------------------- ### Find Player ID Source: https://pkg.robjhyndman.com/cricketdata/reference/find_player_id.html Searches for a player by name on cricinfo.com and returns a table of matching players, their IDs, and the teams they played for. ```APIDOC ## find_player_id ### Description Find a player id from cricinfo.com. ### Usage ```R find_player_id(searchstring) ``` ### Arguments * `searchstring` (character vector) - Part of a player name(s) to search for. ### Value A table of matching players, their ids, and teams they played for. ### See Also `fetch_player_data()`, `fetch_player_meta()` ### Examples ```R if (FALSE) { # Find player ID for 'Perry' (perry <- find_player_id("Perry")) # Fetch player data using the found ID EllysePerry <- fetch_player_data(perry[2, "ID"], "test") } ``` ``` -------------------------------- ### Plot ODI Scores with ggplot2 Source: https://pkg.robjhyndman.com/cricketdata/articles/cricinfo.html Generates a scatter plot of runs scored against the date for ODI matches. Includes a horizontal line at the average score and uses color to indicate if the player was not out. Requires the ggplot2 library and a data frame named MegLanning with Date, Runs, NotOut, and MLave columns. ```r ggplot(MegLanning) + geom_hline(aes(yintercept = MLave), col = "gray") + geom_point(aes(x = Date, y = Runs, col = NotOut)) + ggtitle("Meg Lanning ODI Scores") + scale_y_continuous(sec.axis = sec_axis(~., breaks = MLave)) ``` -------------------------------- ### fetch_player_data Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_player_data.html Fetches individual player data from all matches played. The function will scrape the data from ESPNCricinfo and return a tibble with one line per innings for all games a player has played. To identify a player, use their Cricinfo player ID. ```APIDOC ## fetch_player_data ### Description Fetches individual player data from all matches played. The function will scrape the data from ESPNCricinfo and return a tibble with one line per innings for all games a player has played. To identify a player, use their Cricinfo player ID. The simplest way to find this is to look up their Cricinfo Profile page. The number at the end of the URL is the ID. For example, Meg Lanning's profile page is http://www.espncricinfo.com/australia/content/player/329336.html, so her ID is 329336. ### Usage ```R fetch_player_data( playerid, matchtype = c("test", "odi", "t20"), activity = c("batting", "bowling", "fielding") ) ``` ### Arguments * **playerid** (Integer or character) - The player ID as given in the Cricinfo profile. * **matchtype** (character vector) - Which type of cricket matches do you want? Tests, ODIs or T20s? Not case-sensitive. Defaults to c("test", "odi", "t20"). * **activity** (character vector) - Which type of activities do you want? Batting, Bowling or Fielding? Not case-sensitive. Defaults to c("batting", "bowling", "fielding"). ### Value A tibble containing data on the selected player, with one row for every innings of every match in which they have played. ### Examples ```R # Download data on some players EllysePerry <- fetch_player_data(275487, "T20", "batting") RahulDravid <- fetch_player_data(28114, "ODI", "fielding") LasithMalinga <- fetch_player_data(49758, "Test", "bowling") # Create a plot for Ellyse Perry's T20 scores library(dplyr) library(ggplot2) EllysePerry |> filter(!is.na(Runs)) |> ggplot(aes(x = Start_Date, y = Runs, col = Dismissal, na.rm = TRUE)) + geom_point() + ggtitle("Ellyse Perry's T20 Scores") ``` ``` -------------------------------- ### Calculate Team Strike Rates per Innings Source: https://pkg.robjhyndman.com/cricketdata/articles/cricsheet.html Calculates rolling strike rates, identifies wicket balls, and creates descriptive labels for each innings. Excludes matches with 'tie' or 'no result' outcomes. ```r team_strike_rate <- wbbl07_bbb_tidy |> # Exclude matches that ended with a Super Over ("tie") # and matches that were called off ("no result") filter(!outcome_batting_team %in% c("tie", "no result")) |> group_by(match_id, innings) |> mutate( rolling_strike_rate = round( runs_cumulative / balls_cumulative * 100, 1 ), wicket_ball_num = case_when( !is.na(wicket_type) ~ balls_cumulative, TRUE ~ NA_real_ ), wicket_strike_rate = case_when( !is.na(wicket_type) ~ rolling_strike_rate, TRUE ~ NA_real_ ), innings_description = case_when( innings == 1 ~ "Batting 1st", innings == 2 ~ "Batting 2nd" ), bowling_team_short = word(bowling_team, -1), start_date_day = lubridate::day(start_date), start_date_month = lubridate::month(start_date), match_details = glue::glue( "{innings_description} vs. {bowling_team_short} ({start_date_day}/{start_date_month})" ) ) |> arrange(match_id, innings, balls_cumulative) |> mutate( match_details = factor( match_details, levels = unique(match_details) ), outcome_batting_team = factor( outcome_batting_team, levels = c("won", "lost") ) ) ``` -------------------------------- ### Fetch Cricinfo Data Function Signature Source: https://pkg.robjhyndman.com/cricketdata/reference/fetch_cricinfo.html Defines the signature for the `fetch_cricinfo` function, specifying available arguments for match type, sex, activity, data type, and country. ```R fetch_cricinfo( matchtype = c("test", "odi", "t20"), sex = c("men", "women"), activity = c("batting", "bowling", "fielding"), type = c("career", "innings"), country = NULL ) ``` -------------------------------- ### Fetch Player Data by ID Source: https://pkg.robjhyndman.com/cricketdata/articles/cricketdata_R_pkg.html Retrieve all match data for a player using their Cricinfo ID. This function scrapes data from ESPNCricinfo and returns a tibble. You can specify match type and activity (batting/bowling/fielding). ```R # Fetching the player Meg Lanning's playing data MegLanning <- fetch_player_data(meg_lanning_id, "ODI") |> mutate(NotOut = (Dismissal == "not out")) ``` ```R dim(MegLanning) #> [1] 103 14 names(MegLanning) #> [1] "Date" "Innings" "Opposition" "Ground" "Runs" #> [6] "Mins" "BF" "X4s" "X6s" "SR" #> [11] "Pos" "Dismissal" "Inns" "NotOut" ``` ```R # Compute batting average MLave <- MegLanning |> filter(!is.na(Runs)) |> summarise(Average = sum(Runs) / (n() - sum(NotOut))) |> pull(Average) names(MLave) <- paste("Average =", round(MLave, 2)) # Plot ODI scores ggplot(MegLanning) + geom_hline(aes(yintercept = MLave), col = "gray") + geom_point(aes(x = Date, y = Runs, col = NotOut)) + ggtitle("Meg Lanning ODI Scores") + scale_y_continuous(sec.axis = sec_axis(~., breaks = MLave)) ```