R/get_user_drafts.R

Defines functions get_user_drafts

Documented in get_user_drafts

#' Gather User Draft Information
#'
#' Given a user ID, sport abbreviation, and season number, gather draft information for that selection.
#'
#' @return Returns a data frame containing information about the draft(s).
#' @author Nick Bultman, \email{njbultman74@@gmail.com}, December 2021
#' @keywords user draft
#' @importFrom httr GET content
#' @importFrom jsonlite fromJSON
#' @export
#' @examples
#' \dontrun{get_user_drafts(688556535013502976, "nfl", 2021)}
#'
#' @param user_id User ID generated by Sleeper (numeric)
#' @param sport Sport that you would like to query ("nfl" only supported currently) (character)
#' @param season Season that you would like to select (numeric)
#'
get_user_drafts <- function(user_id, sport, season) {
  # Check if sport parameter is of type character
  if(!is.character(sport)) {
    # If type character, inform user and stop function
    stop("sport parameter must be of type character")
  # Check if season parameter is of type numeric
  } else if(!is.numeric(season)) {
    # If type numeric, inform user and stop function
    stop("season parameter must be of type numeric")
  }
  # Execute query to API given inputs specified
  x <- jsonlite::fromJSON(httr::content(httr::GET(paste0("https://api.sleeper.app/v1/user/", user_id, "/drafts/", 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_settings <- x$settings
    x_metadata <- x$metadata
    # Remove nested data frames from original query
    x$settings <- NULL
    x$metadata <- NULL
    # Bind broken out data frames to main query
    x_fin <- cbind(x, 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.