R/MLB_Season.R

Defines functions MLB_Season

Documented in MLB_Season

#' Web Scrape for MLB Season Batting or Pitching Data
#'
#' @param year MLB Season Year of Interest
#' @param BorP Batting or Pitching Data
#'
#' @return Data Table of Batting/Pitching Data for a Specific MLB Season
#' @export
#'
#' @importFrom rvest html_table
#' @importFrom xml2 read_html
#' @examples
#' year = 2021
#' BorP = 'B'
#' Batting.2021 = MLB_Season(year, BorP)

MLB_Season <- function(year, BorP){
  Bhtml <- paste0('https://www.baseball-reference.com/leagues/majors/',year,'.shtml')
  Bhtml.read <- read_html(Bhtml)
  Btable <- as.data.frame(html_table(Bhtml.read))
  Btable2 <- Btable[1:(nrow(Btable)-3),]

  Phtml <- paste0('https://www.baseball-reference.com/leagues/majors/',year,'-standard-pitching.shtml')
  Phtml.read <- read_html(Phtml)
  Ptable <- as.data.frame(html_table(Phtml.read))
  Ptable2 <- Ptable[1:(nrow(Btable)-3),]

  if (BorP == 'B'){
    return(Btable2)
  }else if (BorP == 'P')
    return(Ptable2)
}
madeline-peyton/B581Final documentation built on Dec. 23, 2021, 11:16 p.m.