R/get_user_leagues.R

Defines functions get_user_leagues

Documented in get_user_leagues

#' Gather Leagues for User
#'
#' Given a user ID and optional sport and season, grab the league data concerning that particular user. 
#' This includes total rosters, scoring settings, roster positions, and more.
#'
#' @return Returns a data frame containing information about the user.
#' @author Nick Bultman, \email{njbultman74@@gmail.com}, September 2021
#' @keywords league user
#' @importFrom httr GET content
#' @importFrom jsonlite fromJSON
#' @export
#' @examples
#' \dontrun{get_user_leagues(688556535013502976)}
#' \dontrun{get_user_leagues("688556535013502976", sport = "nfl", season = "2021")}
#'
#' @param user_id User ID generated by Sleeper (numeric or character)
#' @param sport Sport for league information (character)
#' @param season Season for league information (numeric or character)
#'
get_user_leagues <- function(user_id, sport = "nfl", season = substr(Sys.Date(), start = 1, stop = 4)) {
  # Check to see if sport parameter is of type character
  if(!is.character(sport)) {
    # If not character, stop function and inform user
    stop("sport parameter must be of type character")
  }
  # Execute query to API given inputs specified
  x <- jsonlite::fromJSON(httr::content(httr::GET(paste0("https://api.sleeper.app/v1/user/", user_id, "/leagues/", sport, "/", season)), as = "text"))
  # Check if length of returned object is zero
  if(length(x) == 0) {
    # If length is zero, inform user and return nothing
    message("No data was returned - are you sure all parameters were inputted correctly?")
  } else {
    # If length is not zero, break out nested data frames
    x_scoring_settings <- x$scoring_settings
    x_settings <- x$settings
    x_metadata <- x$metadata
    # Remove nested data frames from main query
    x$scoring_settings <- NULL
    x$settings <- NULL
    x$metadata <- NULL
    # Merge broken out data frames to main query
    x_fin <- cbind(x, x_scoring_settings, x_settings, x_metadata)
    # 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.