R/get_matchups.R

Defines functions get_matchups

Documented in get_matchups

#' Gather Matchup Data in a League for a Week
#'
#' Given a league ID and week number, grab the matchup data, including player points, total points,
#' starting rosters, and more.
#'
#' @return Returns a data frame containing information about the matchups.
#' @author Nick Bultman, \email{njbultman74@@gmail.com}, September 2021
#' @keywords matchups league
#' @importFrom httr GET content
#' @importFrom jsonlite fromJSON
#' @export
#' @examples
#' \dontrun{get_matchups(688281863499907072, 2)}
#' \dontrun{get_matchups("688281863499907072", 1)}
#'
#' @param league_id League ID generated by Sleeper (numeric or character)
#' @param week Matchup week (numeric)
#'
get_matchups <- function(league_id, week) {
  # Check class of week parameter to see if numeric
  if(!is.numeric(week)) {
    # If not numeric, inform user and halt function
    stop("week paramater must be numeric")
  } else {
    # If numeric, execute query to API given inputs specified
    x <- jsonlite::fromJSON(httr::content(httr::GET(paste0("https://api.sleeper.app/v1/league/", league_id, "/matchups/", week)), as = "text"))
  }
  # Check if returned object is of class list
  if(inherits(x, "list")) {
    # If list, inform user and return nothing
    message("No data found. Was the week entered a valid week in terms of your season settings?")
    # If not list, check if NULL
  } else if(is.null(x)) {
    # If NULL, inform user and return nothing
    message("No data found. Was the league ID entered correctly?")
  } else {
    # If not NULL, break out nested data frame
    x_player_points <- x$players_points
    # Remove nested data frame from main query
    x$players_points <- NULL
    # Bind broken out data frame to main query
    x_fin <- cbind(x, x_player_points)
    # Return final data frame
    return(x_fin)
  }
}

Try the sleeperapi package in your browser

Any scripts or data that you put into this service are public.

sleeperapi documentation built on June 22, 2024, 9:29 a.m.