R/get_league.R

Defines functions get_league

Documented in get_league

#' Gather League Data
#'
#' Given a league ID, grab the data for that league. Includes roster positions, season type, if it is in
#' season, and more.
#'
#' @return Returns a data frame containing information about the league.
#' @author Nick Bultman, \email{njbultman74@@gmail.com}, September 2021
#' @keywords user users
#' @importFrom httr GET content
#' @importFrom jsonlite fromJSON
#' @export
#' @examples
#' \dontrun{get_league(688281863499907072)}
#'
#' @param league_id League ID generated by Sleeper (numeric or character)
#'
get_league <- function(league_id) {
  # Execute query to API given league ID specified
  x <- jsonlite::fromJSON(httr::content(httr::GET(paste0("https://api.sleeper.app/v1/league/", league_id)), as = "text"))
  # Check if returned object is NULL
  if(is.null(x)) {
    # If NULL, inform user and return nothing
    message("League ID did not return any results. Did you enter the league ID correctly?")
  } else {
    # If not NULL, parse original list to data frame object, ignoring nested data frames
    x_df <- do.call(data.frame, args = list(stringsAsFactors = FALSE, Filter(function(z) length(z) == 1, x)))
    # Split out nested data frames in original list object
    x_df_settings <- do.call(data.frame, list(stringsAsFactors = FALSE, x$settings))
    x_df_metadata <- do.call(data.frame, list(stringsAsFactors = FALSE, x$metadata))
    # Bind all data frames together
    x_df_fin <- cbind(x_df, x_df_settings, x_df_metadata)
    # Return final data frame
    return(x_df_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.