R/MLB_Team.R

Defines functions MLB_Team

Documented in MLB_Team

#' Web Scrape for MLB Team Pitching/Batting Data
#'
#' @param TeamAbbr Abbreviation for MLBTeam
#' @param year MLB Season Year of Interest
#' @param BorP Batting or Pitching Data
#'
#' @return
#' @export
#'
#' @importFrom rvest html_table
#' @importFrom xml2 read_html
#' @examples
#' TeamAbbr = 'CIN'
#' year = 1987
#' BorP = 'P'
#' CIN_1987_P = MLB_Team(TeamAbbr, year, BorP)
MLB_Team <- function(TeamAbbr, year, BorP){
  html <- paste0('https://www.baseball-reference.com/teams/',TeamAbbr,'/',year,'.shtml')
  html.read <- read_html(html)
  tables <- html_table(html.read)
  Btable1 <- as.data.frame(tables[1])
  Btable2 <- Btable1[1:(nrow(Btable1)-5),]
  Btable3 <- Btable2[!(Btable2$Rk == 'Rk'),]
  Ptable1 <- as.data.frame(tables[2])
  Ptable2 <- Ptable1[1:(nrow(Ptable1)-3),]
  Ptable3 <- Ptable2[!(Ptable2$Rk == 'Rk'),]

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