content
stringlengths
0
14.9M
filename
stringlengths
44
136
register_s3_method <- function(pkg, generic, class, fun = NULL) { stopifnot(is.character(pkg), length(pkg) == 1) stopifnot(is.character(generic), length(generic) == 1) stopifnot(is.character(class), length(class) == 1) if (is.null(fun)) { fun <- get(paste0(generic, ".", class), envir = parent.frame()) } else { stopifnot(is.function(fun)) } if (pkg %in% loadedNamespaces()) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } # Always register hook in case package is later unloaded & reloaded setHook( packageEvent(pkg, "onLoad"), function(...) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } ) } .onLoad <- function(...) { # webshot provides methods for knitr::knit_print, but knitr isn't a Depends # or Imports of htmltools, only an Enhances. This code snippet manually # registers our method(s) with S3 once both webshot2 and knitr are loaded. register_s3_method("knitr", "knit_print", "webshot") }
/scratch/gouwar.j/cran-all/cranData/webshot2/R/zzz.R
# Generated by cpp11: do not edit by hand wsCreate <- function(uri, loop_id, robjPublic, robjPrivate, accessLogChannels, errorLogChannels, maxMessageSize) { .Call(`_websocket_wsCreate`, uri, loop_id, robjPublic, robjPrivate, accessLogChannels, errorLogChannels, maxMessageSize) } wsAppendHeader <- function(wsc_xptr, key, value) { invisible(.Call(`_websocket_wsAppendHeader`, wsc_xptr, key, value)) } wsAddProtocols <- function(wsc_xptr, protocols) { invisible(.Call(`_websocket_wsAddProtocols`, wsc_xptr, protocols)) } wsConnect <- function(wsc_xptr) { invisible(.Call(`_websocket_wsConnect`, wsc_xptr)) } wsSend <- function(wsc_xptr, msg) { invisible(.Call(`_websocket_wsSend`, wsc_xptr, msg)) } wsClose <- function(wsc_xptr, code, reason) { invisible(.Call(`_websocket_wsClose`, wsc_xptr, code, reason)) } wsProtocol <- function(wsc_xptr) { .Call(`_websocket_wsProtocol`, wsc_xptr) } wsState <- function(wsc_xptr) { .Call(`_websocket_wsState`, wsc_xptr) } wsUpdateLogChannels <- function(wsc_xptr, accessOrError, setOrClear, logChannels) { invisible(.Call(`_websocket_wsUpdateLogChannels`, wsc_xptr, accessOrError, setOrClear, logChannels)) }
/scratch/gouwar.j/cran-all/cranData/websocket/R/cpp11.R
#' @useDynLib websocket, .registration = TRUE #' @import later #' @importFrom R6 R6Class NULL # Used to "null out" handler functions after a websocket client is closed null_func <- function(...) { } #' Create a WebSocket client #' #' \preformatted{ #' WebSocket$new(url, #' protocols = character(0), #' headers = NULL, #' autoConnect = TRUE, #' accessLogChannels = c("none"), #' errorLogChannels = NULL, #' maxMessageSize = 32 * 1024 * 1024) #' } #' #' @details #' #' A WebSocket object has four events you can listen for, by calling the #' corresponding `onXXX` method and passing it a callback function. All callback #' functions must take a single `event` argument. The `event` argument is a #' named list that always contains a `target` element that is the WebSocket #' object that originated the event, plus any other relevant data as detailed #' below. #' #' \describe{ #' \item{\code{onMessage}}{Called each time a message is received from the #' server. The event will have a `data` element, which is the message #' content. If the message is text, the `data` will be a one-element #' character vector; if the message is binary, it will be a raw vector.} #' \item{\code{onOpen}}{Called when the connection is established.} #' \item{\code{onClose}}{Called when a previously-opened connection is closed. #' The event will have `code` (integer) and `reason` (one-element character) #' elements that describe the remote's reason for closing.} #' \item{\code{onError}}{Called when the connection fails to be established. #' The event will have an `message` element, a character vector of length 1 #' describing the reason for the error.} #' } #' #' Each `onXXX` method can be called multiple times to register multiple #' callbacks. Each time an `onXXX` is called, its (invisible) return value is a #' function that can be invoked to cancel that particular registration. #' #' A WebSocket object also has the following methods: #' #' \describe{ #' \item{\code{connect()}}{Initiates the connection to the server. (This does #' not need to be called unless you have passed `autoConnect=FALSE` to the #' constructor.)} #' \item{\code{send(msg)}}{Sends a message to the server.} #' \item{\code{close()}}{Closes the connection.} #' \item{\code{readyState()}}{Returns an integer representing the state of the #' connection. #' \describe{ #' \item{\code{0L}: Connecting}{The WebSocket has not yet established a #' connection with the server.} #' \item{\code{1L}: Open}{The WebSocket has connected and can send and #' receive messages.} #' \item{\code{2L}: Closing}{The WebSocket is in the process of closing.} #' \item{\code{3L}: Closed}{The WebSocket has closed, or failed to open.} #' }} #' \item{setAccessLogChannels(channels)}{Enable the websocket Access channels after the #' websocket's creation. A value of \code{NULL} will not enable any new Access channels.} #' \item{setErrorLogChannels(channels)}{Enable the websocket Error channels after the #' websocket's creation. A value of \code{NULL} will not enable any new Error channels.} #' \item{clearAccessLogChannels(channels)}{Disable the websocket Access channels after the #' websocket's creation. A value of \code{NULL} will not clear any existing Access channels.} #' \item{clearErrorLogChannels(channels)}{Disable the websocket Error channels after the #' websocket's creation. A value of \code{NULL} will not clear any existing Error channels.} #' } #' #' @param url The WebSocket URL. Should begin with \code{ws://} or \code{wss://}. #' @param protocols Zero or more WebSocket sub-protocol names to offer to the server #' during the opening handshake. #' @param headers A named list or character vector representing keys and values #' of headers in the initial HTTP request. #' @param autoConnect If set to `FALSE`, then constructing the WebSocket object #' will not automatically cause the connection to be established. This can be #' used if control will return to R before event handlers can be set on the #' WebSocket object (i.e. you are constructing a WebSocket object manually at #' an interactive R console); after you are done attaching event handlers, you #' must call `ws$connect()` to establish the WebSocket connection. #' @param accessLogChannels A character vector of access log channels that are #' enabled. Defaults to \code{"none"}, which displays no normal, websocketpp logging activity. #' Setting \code{accessLogChannels = NULL} will use default websocketpp behavior. #' Multiple access logging levels may be passed in for them to be enabled. #' #' A few commonly used access logging values are: #' \describe{ #' \item{\code{"all"}}{Special aggregate value representing "all levels"} #' \item{\code{"none"}}{Special aggregate value representing "no levels"} #' \item{\code{"rerror"}}{Recoverable error. Recovery may mean cleanly closing the connection #' with an appropriate error code to the remote endpoint.} #' \item{\code{"fatal"}}{Unrecoverable error. This error will trigger immediate unclean #' termination of the connection or endpoint.} #' } #' #' All logging levels are explained in more detail at \url{https://docs.websocketpp.org/reference_8logging.html}. #' @param errorLogChannels A character vector of error log channels that are #' displayed. The default value is \code{NULL}, which will use default websocketpp behavior. #' Multiple error logging levels may be passed in for them to be enabled. #' #' A few commonly used error logging values are: #' \describe{ #' \item{\code{"all"}}{Special aggregate value representing "all levels"} #' \item{\code{"none"}}{Special aggregate value representing "no levels"} #' \item{\code{"connect"}}{One line for each new connection that is opened} #' \item{\code{"disconnect"}}{One line for each new connection that is closed} #' } #' #' All logging levels are explained in more detail at \url{https://docs.websocketpp.org/reference_8logging.html}. #' @param maxMessageSize The maximum size of a message in bytes. If a message #' larger than this is sent, the connection will fail with the \code{message_too_big} #' protocol error. #' #' #' @name WebSocket #' #' @examples #' ## Only run this example in interactive R sessions #' if (interactive()) { #' #' # Create a websocket using the websocket.org test server #' ws <- WebSocket$new("ws://echo.websocket.org/") #' ws$onMessage(function(event) { #' cat("Client got msg:", event$data, "\n") #' }) #' ws$onClose(function(event) { #' cat("Client disconnected\n") #' }) #' ws$onOpen(function(event) { #' cat("Client connected\n") #' }) #' #' # Try sending a message with ws$send("hello"). #' # Close the websocket with ws$close() after you're done with it. #' } NULL #' @export WebSocket <- R6Class("WebSocket", public = list( initialize = function(url, protocols = character(0), headers = NULL, autoConnect = TRUE, accessLogChannels = c("none"), errorLogChannels = NULL, maxMessageSize = 32 * 1024 * 1024, loop = later::current_loop() ) { private$callbacks <- new.env(parent = emptyenv()) private$callbacks$open <- Callbacks$new() private$callbacks$close <- Callbacks$new() private$callbacks$error <- Callbacks$new() private$callbacks$message <- Callbacks$new() if (length(maxMessageSize) != 1 || !is.numeric(maxMessageSize) || maxMessageSize < 0){ stop("maxMessageSize must be a non-negative integer") } private$wsObj <- wsCreate( url, loop$id, self, private, private$accessLogChannels(accessLogChannels, "none"), private$errorLogChannels(errorLogChannels, "none"), maxMessageSize ) mapply(names(headers), headers, FUN = function(key, value) { wsAppendHeader(private$wsObj, key, value) }) wsAddProtocols(private$wsObj, protocols) private$pendingConnect <- TRUE if (autoConnect) { self$connect() } }, connect = function() { if (private$pendingConnect) { private$pendingConnect <- FALSE wsConnect(private$wsObj) } else { warning("Ignoring extraneous connect() call (did you mean to have autoConnect=FALSE in the constructor?)") } }, readyState = function() { code <- function(value, desc) { structure(value, description = desc) } if (private$pendingConnect) { return(code(-1L, "Pre-connecting")) } switch(wsState(private$wsObj), INIT = code(0L, "Connecting"), OPEN = code(1L, "Open"), CLOSING = code(2L, "Closing"), CLOSED = code(3L, "Closed"), FAILED = code(3L, "Closed"), stop("Unknown state ", wsState(private$wsObj)) ) }, onOpen = function(callback) { invisible(private$callbacks[["open"]]$register(callback)) }, onClose = function(callback) { invisible(private$callbacks[["close"]]$register(callback)) }, onError = function(callback) { invisible(private$callbacks[["error"]]$register(callback)) }, onMessage = function(callback) { invisible(private$callbacks[["message"]]$register(callback)) }, protocol = function() { wsProtocol(private$wsObj) }, send = function(msg) { wsSend(private$wsObj, msg) }, close = function(code = 1000L, reason = "") { wsClose(private$wsObj, code, reason) }, setAccessLogChannels = function(channels = c("all")) { wsUpdateLogChannels(private$wsObj, "access", "set", private$accessLogChannels(channels, "none")) }, setErrorLogChannels = function(channels = c("all")) { wsUpdateLogChannels(private$wsObj, "error", "set", private$errorLogChannels(channels, "none")) }, clearAccessLogChannels = function(channels = c("all")) { wsUpdateLogChannels(private$wsObj, "access", "clear", private$accessLogChannels(channels, "all")) }, clearErrorLogChannels = function(channels = c("all")) { wsUpdateLogChannels(private$wsObj, "error", "clear", private$errorLogChannels(channels, "all")) } ), private = list( wsObj = NULL, callbacks = NULL, pendingConnect = TRUE, getInvoker = function(eventName) { callbacks <- private$callbacks[[eventName]] stopifnot(!is.null(callbacks)) callbacks$invoke }, accessLogChannelValues = c( "none", "connect", "disconnect", "control", "frame_header", "frame_payload", "message_header", "message_payload", "endpoint", "debug_handshake", "debug_close", "devel", "app", "http", "fail", "access_core", "all" ), errorLogChannelValues = c("none", "devel", "library", "info", "warn", "rerror", "fatal", "all"), accessLogChannels = function(channels, stompValue) { if (is.null(channels)) return(character(0)) channels <- match.arg(channels, private$accessLogChannelValues, several.ok = TRUE) if (stompValue %in% channels) channels <- stompValue channels }, errorLogChannels = function(channels, stompValue) { if (is.null(channels)) return(character(0)) channels <- match.arg(channels, private$errorLogChannelValues, several.ok = TRUE) if (stompValue %in% channels) channels <- stompValue channels } ) ) Callbacks <- R6Class( 'Callbacks', private = list( .nextId = integer(0), .callbacks = 'environment' ), public = list( initialize = function() { # NOTE: we avoid using '.Machine$integer.max' directly # as R 3.3.0's 'radixsort' could segfault when sorting # an integer vector containing this value private$.nextId <- as.integer(.Machine$integer.max - 1L) private$.callbacks <- new.env(parent = emptyenv()) }, register = function(callback) { if (!is.function(callback)) { stop("callback must be a function") } id <- as.character(private$.nextId) private$.nextId <- private$.nextId - 1L private$.callbacks[[id]] <- callback return(function() { rm(list = id, pos = private$.callbacks) }) }, invoke = function(...) { # Ensure that calls are invoked in the order that they were registered keys <- as.character(sort(as.integer(ls(private$.callbacks)), decreasing = TRUE)) callbacks <- mget(keys, private$.callbacks) for (callback in callbacks) { tryCatch( callback(...), error = function(e) { message("Error in websocket callback: ", e$message) }, interrupt = function(e) { message("Interrupt received while executing websocket callback.") } ) } }, count = function() { length(ls(private$.callbacks)) } ) )
/scratch/gouwar.j/cran-all/cranData/websocket/R/websocket.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ---- eval = FALSE------------------------------------------------------------ # ws <- WebSocket$new("ws://echo.websocket.org/") ## ---- eval = FALSE------------------------------------------------------------ # ws <- WebSocket$new("ws://echo.websocket.org/", autoConnect = FALSE) # # Set up callbacks here... # ws$connect() ## ---- eval = FALSE------------------------------------------------------------ # { # ws <- WebSocket$new("ws://echo.websocket.org/") # ws$onOpen(function(event) { message("websocket opened") }) # } ## ---- eval = FALSE------------------------------------------------------------ # { # ws <- WebSocket$new("ws://echo.websocket.org/") # ws$onOpen(function(event) { # cat("connected\n") # }) # } ## ---- eval = FALSE------------------------------------------------------------ # { # ws <- WebSocket$new("ws://echo.websocket.org/") # removeThis <- ws$onMessage(function(event) { # cat("this is the last time i'll run\n") # removeThis() # }) # ws$onOpen(function(event) { # ws$send("one") # ws$send("two") # }) # }
/scratch/gouwar.j/cran-all/cranData/websocket/inst/doc/overview.R
--- title: "Overview" date: "2019-03-18" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Overview} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` `websocket` is a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) client package for R backed by the [websocketpp](https://github.com/zaphoyd/websocketpp) C++ library. WebSocket clients are most commonly used from [JavaScript in a web browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications), and their use in R with this package is not much different. The experience of using `websocket` is designed to be similar to the experience of using WebSockets in a browser. Like WebSockets in a browser, `websocket` makes it easy to asynchronously process data from a WebSocket server. In the context of an R or Shiny application, this functionality is useful for incrementally consuming data from an external data source presented as a WebSocket server. The I/O for a WebSocket happens on a separate thread from the main R thread; there is one thread for each WebSocket. ## Creating WebSockets WebSockets are represented as instances of an [R6](https://github.com/r-lib/R6) object, and are created with `$new()`: ```{r, eval = FALSE} ws <- WebSocket$new("ws://echo.websocket.org/") ``` By default, and similarly to how WebSockets in JavaScript work, constructing a WebSocket with `$new()` will automatically initiate the WebSocket connection. In normal usage, such as in a Shiny app or from within a function, this default behavior is ideal. When run interactively from the R console however, the default behavior is problematic. The reason is that the connection will open before the user is given an opportunity to register any event handlers, meaning messages from the server could be dropped. So, in the console, WebSockets should be created like this: ```{r, eval = FALSE} ws <- WebSocket$new("ws://echo.websocket.org/", autoConnect = FALSE) # Set up callbacks here... ws$connect() ``` ## Interaction with `later` The technical reason that `autoConnect = FALSE` is necessary at the console has to do with how [later](https://github.com/r-lib/later) works. `later` is a package that provides an event loop for R, and the `websocket` package uses it to schedule callbacks that run in response to WebSocket events (like incoming messages). When a function has been put in to the queue with `later`, there are two ways it could be executed. One way is when `later::run_now()` is called. The second way is when the R console is idle (and the R call stack is empty): when that happens, `later` will automatically execute callbacks from the queue. When running a block of code like this in a function, or surrounded with `{` and `}`, the console does not have a chance to be idle in between the lines of code: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") ws$onOpen(function(event) { message("websocket opened") }) } ``` In this code, the WebSocket has queued a connection attempt before `ws$onOpen()` is called. However, the `ws$onOpen()` runs _before_ R tries to call any `onOpen` callbacks, because there were no idle "ticks" between the two lines of code for `later` to respond to any opened connections. (Technical note: `websocket` runs the I/O on a separate thread; when an event occurs, like an open event or message, it uses `later` to schedule a callback to run on the main R thread. In the case above, the WebSocket connection could actually be opened -- on the I/O thread -- before the main R thread calls `ws$onOpen()` to set up the callback. If that happened it would only be able to schedule the invocation of the `onOpen` callback immediately; only at a later point in time, when the R console is idle, or when `later::run_now()` is called, would it be able to actually execute the callbacks. So in the example above, the `onOpen` callback is guaranteed to run when the connection is successfully opened.) Because `$new()` only *schedules* the work of connecting &mdash; it does not perform it immediately &mdash; it's safe within a code block to attach handlers, because none of them can possibly run until after the enclosing block returns. ## Adding handlers After a `WebSocket` object is created, you have an opportunity to associate handler functions with various WebSocket events using the following R6 methods: 1. `$onOpen()`: Invoked when the connection is first opened 1. `$onMessage()`: Invoked when a message is received from the server 1. `$onClose()`: Invoked when the client or server closes the connection 1. `$onError()`: Invoked when an error occurs For example, the following code instantiates a WebSocket, installs an `onOpen` handler, and prints a message once the WebSocket is open: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") ws$onOpen(function(event) { cat("connected\n") }) } ``` > Note that because the `$new()` and `$onOpen()` calls are within the same code block, `autoConnect` does not need to be `FALSE`. ### Event environment Every handler function is passed an `event` environment. This environment contains at least the entry `target`, which is a reference to the WebSocket object on which the event occurred. In addition to `target`, other entries are available depending on the handler type: * `$onMessage()` * `data`: Text or binary data received from the server, as a character vector or raw vector, respectively * `$onClose()` * `code`: The numeric [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) * `reason`: Character vector, the reason for closing * `$onError()` * `message`: Character vector, an error message ## Removing handlers Multiple handler functions for the same event type can be added to the WebSocket by repeatedly calling a handler registration method such as `$onMessage()`. The return value of every registration method is a zero-argument function that may be invoked to **deregister** the handler function. The following is an example of an `$onMessage()` handler that immediately removes itself: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") removeThis <- ws$onMessage(function(event) { cat("this is the last time i'll run\n") removeThis() }) ws$onOpen(function(event) { ws$send("one") ws$send("two") }) } ``` Even though `ws$send()` is called twice in the `$onOpen()` handler function, the `$onMessage()` handler function is only run once. ### Other notes * As long as a WebSocket object has an open connection, it will not be eligible for garbage collection, even if you lose all your references to the object, because the callback scheduling system maintains a reference to the object. This means that any callbacks on the WebSocket will continue to execute. If the connection is closed, the callback scheduling system will drop its references to the WebSocket object, and it will then be eligible for garbage collection.
/scratch/gouwar.j/cran-all/cranData/websocket/inst/doc/overview.Rmd
# Build against mingw-w64 build of openssl VERSION <- commandArgs(TRUE) if(!file.exists(sprintf("../windows/openssl-%s/include/openssl/ssl.h", VERSION))){ if(getRversion() < "3.3.0") setInternet2() download.file(sprintf("https://github.com/rwinlib/openssl/archive/v%s.zip", VERSION), "lib.zip", quiet = TRUE) dir.create("../windows", showWarnings = FALSE) unzip("lib.zip", exdir = "../windows") unlink("lib.zip") }
/scratch/gouwar.j/cran-all/cranData/websocket/tools/winlibs.R
--- title: "Overview" date: "2019-03-18" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Overview} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` `websocket` is a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) client package for R backed by the [websocketpp](https://github.com/zaphoyd/websocketpp) C++ library. WebSocket clients are most commonly used from [JavaScript in a web browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications), and their use in R with this package is not much different. The experience of using `websocket` is designed to be similar to the experience of using WebSockets in a browser. Like WebSockets in a browser, `websocket` makes it easy to asynchronously process data from a WebSocket server. In the context of an R or Shiny application, this functionality is useful for incrementally consuming data from an external data source presented as a WebSocket server. The I/O for a WebSocket happens on a separate thread from the main R thread; there is one thread for each WebSocket. ## Creating WebSockets WebSockets are represented as instances of an [R6](https://github.com/r-lib/R6) object, and are created with `$new()`: ```{r, eval = FALSE} ws <- WebSocket$new("ws://echo.websocket.org/") ``` By default, and similarly to how WebSockets in JavaScript work, constructing a WebSocket with `$new()` will automatically initiate the WebSocket connection. In normal usage, such as in a Shiny app or from within a function, this default behavior is ideal. When run interactively from the R console however, the default behavior is problematic. The reason is that the connection will open before the user is given an opportunity to register any event handlers, meaning messages from the server could be dropped. So, in the console, WebSockets should be created like this: ```{r, eval = FALSE} ws <- WebSocket$new("ws://echo.websocket.org/", autoConnect = FALSE) # Set up callbacks here... ws$connect() ``` ## Interaction with `later` The technical reason that `autoConnect = FALSE` is necessary at the console has to do with how [later](https://github.com/r-lib/later) works. `later` is a package that provides an event loop for R, and the `websocket` package uses it to schedule callbacks that run in response to WebSocket events (like incoming messages). When a function has been put in to the queue with `later`, there are two ways it could be executed. One way is when `later::run_now()` is called. The second way is when the R console is idle (and the R call stack is empty): when that happens, `later` will automatically execute callbacks from the queue. When running a block of code like this in a function, or surrounded with `{` and `}`, the console does not have a chance to be idle in between the lines of code: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") ws$onOpen(function(event) { message("websocket opened") }) } ``` In this code, the WebSocket has queued a connection attempt before `ws$onOpen()` is called. However, the `ws$onOpen()` runs _before_ R tries to call any `onOpen` callbacks, because there were no idle "ticks" between the two lines of code for `later` to respond to any opened connections. (Technical note: `websocket` runs the I/O on a separate thread; when an event occurs, like an open event or message, it uses `later` to schedule a callback to run on the main R thread. In the case above, the WebSocket connection could actually be opened -- on the I/O thread -- before the main R thread calls `ws$onOpen()` to set up the callback. If that happened it would only be able to schedule the invocation of the `onOpen` callback immediately; only at a later point in time, when the R console is idle, or when `later::run_now()` is called, would it be able to actually execute the callbacks. So in the example above, the `onOpen` callback is guaranteed to run when the connection is successfully opened.) Because `$new()` only *schedules* the work of connecting &mdash; it does not perform it immediately &mdash; it's safe within a code block to attach handlers, because none of them can possibly run until after the enclosing block returns. ## Adding handlers After a `WebSocket` object is created, you have an opportunity to associate handler functions with various WebSocket events using the following R6 methods: 1. `$onOpen()`: Invoked when the connection is first opened 1. `$onMessage()`: Invoked when a message is received from the server 1. `$onClose()`: Invoked when the client or server closes the connection 1. `$onError()`: Invoked when an error occurs For example, the following code instantiates a WebSocket, installs an `onOpen` handler, and prints a message once the WebSocket is open: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") ws$onOpen(function(event) { cat("connected\n") }) } ``` > Note that because the `$new()` and `$onOpen()` calls are within the same code block, `autoConnect` does not need to be `FALSE`. ### Event environment Every handler function is passed an `event` environment. This environment contains at least the entry `target`, which is a reference to the WebSocket object on which the event occurred. In addition to `target`, other entries are available depending on the handler type: * `$onMessage()` * `data`: Text or binary data received from the server, as a character vector or raw vector, respectively * `$onClose()` * `code`: The numeric [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) * `reason`: Character vector, the reason for closing * `$onError()` * `message`: Character vector, an error message ## Removing handlers Multiple handler functions for the same event type can be added to the WebSocket by repeatedly calling a handler registration method such as `$onMessage()`. The return value of every registration method is a zero-argument function that may be invoked to **deregister** the handler function. The following is an example of an `$onMessage()` handler that immediately removes itself: ```{r, eval = FALSE} { ws <- WebSocket$new("ws://echo.websocket.org/") removeThis <- ws$onMessage(function(event) { cat("this is the last time i'll run\n") removeThis() }) ws$onOpen(function(event) { ws$send("one") ws$send("two") }) } ``` Even though `ws$send()` is called twice in the `$onOpen()` handler function, the `$onMessage()` handler function is only run once. ### Other notes * As long as a WebSocket object has an open connection, it will not be eligible for garbage collection, even if you lose all your references to the object, because the callback scheduling system maintains a reference to the object. This means that any callbacks on the WebSocket will continue to execute. If the connection is closed, the callback scheduling system will drop its references to the WebSocket object, and it will then be eligible for garbage collection.
/scratch/gouwar.j/cran-all/cranData/websocket/vignettes/overview.Rmd
#' Create incidence matrix for two-mode networks including audiences #' @description #' `audience_incidence()` created an incidence matrix, which is a matrix A #' with entries `A[i,j]=1` if panelist `i` visited web site `j` at least once. #' Web site can be defined, for example, by the URL's domain, or its host. #' @param wt webtrack data object. #' @param mode2 character. Name of column that includes the second mode (e.g., #' `domain` or `host`) #' @param cutoff visits below this cutoff will not be considered as a visit. #' @return Incidence matrix of a two-mode network #' @seealso To create audience networks see [audience_network]. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- add_duration(wt) #' wt <- suppressWarnings(extract_domain(wt)) #' # create incidence matrix using domains as second mode #' incidence <- audience_incidence(wt) #' # create incidence matrix using hosts as second mode #' wt <- suppressWarnings(extract_host(wt)) #' incidence <- audience_incidence(wt, mode2 = "host") #' } #' @export audience_incidence <- function(wt, mode2 = "domain", cutoff = 3) { # .N = 0 #revisit if (!requireNamespace("igraph", quietly = TRUE)) { stop("The package 'igraph' is needed for this function.") } stopifnot("wt is not an wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", mode2)) el <- wt[duration >= cutoff] el <- el[, c("panelist_id", mode2), with = FALSE] el <- el[, .N, by = c("panelist_id", mode2)] # el <- el[!is.na(domain)] g <- igraph::graph_from_data_frame(el, directed = FALSE) igraph::V(g)$type <- !igraph::bipartite.mapping(g)$type A <- igraph::as_incidence_matrix(g) A } #' Create audience networks #' @description audience network #' @param wt webtrack data object #' @param mode2 character. name of column that includes the second mode (e.g. #' 'domain' or 'host') #' @param cutoff visits below this cutoff will not be considered as a visit #' @param type one of "pmi", "phi", "disparity", "sdsm, "or "fdsm". #' @param alpha significance level #' @return audience network as igraph object #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- add_duration(wt) #' wt <- suppressWarnings(extract_domain(wt)) #' network <- audience_network(wt, type = "pmi", cutoff = 120) #' } #' @export audience_network <- function(wt, mode2 = "domain", cutoff = 3, type = "pmi", alpha = 0.05) { A <- audience_incidence(wt, mode2 = mode2, cutoff = cutoff) type <- match.arg(type, c("pmi", "phi", "disparity", "sdsm", "fdsm")) switch(type, pmi = pmi(A, t = alpha), phi = phi(A, p = alpha), disparity = disparity1(A, p = alpha), sdsm = sdsm1(A, p = alpha), fdsm = fdsm1(A, p = alpha) ) } # network extraction methods ---- pmi <- function(A, t = 0) { reach <- rowSums(A) / ncol(A) exp_mat <- outer(reach, reach, "*") W <- (A %*% t(A)) / ncol(A) B <- log(W / exp_mat) > t igraph::graph_from_adjacency_matrix(B, mode = "undirected", diag = FALSE) } phi <- function(A, p = 0.05) { if (!requireNamespace("stats", quietly = TRUE)) { stop("The package 'stats' is needed for this function.") } D <- (A %*% t(A)) R <- rowSums(A) N <- ncol(A) RR <- suppressWarnings(outer(R, R, "*")) Phi <- (D * N - RR) / sqrt(diag(N - R) %*% RR %*% diag(N - R)) tmat <- Phi * suppressWarnings(sqrt(outer(R, R, "pmax")) - 2) / sqrt(1 - Phi^2) # we cannot use the standard values for big N because we do not have big N pmat <- outer(R, R, function(x, y) stats::qt(p = p / 2, df = pmax(x, y), lower.tail = FALSE)) igraph::graph_from_adjacency_matrix(tmat > pmat, mode = "undirected", diag = FALSE) } disparity1 <- function(A, p = 0.05) { W <- A %*% t(A) diag(W) <- 0 suppressMessages(backbone::disparity(W, class = "igraph", alpha = p)) } sdsm1 <- function(A, p = 0.05) { if (!requireNamespace("backbone", quietly = TRUE)) { stop("The package 'backbone' is needed for this function.") } suppressMessages(backbone::sdsm(A, class = "igraph", alpha = p)) } fdsm1 <- function(A, p = 0.05) { if (!requireNamespace("backbone", quietly = TRUE)) { stop("The package 'backbone' is needed for this function.") } suppressMessages(backbone::sdsm(A, class = "igraph", alpha = p)) }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/audience_networks.R
#' Classify visits by matching to a list of classes #' @description #' `classify_visits()` categorizes visits by either extracting the visit URL's #' domain or host and matching them to a list of domains or hosts; #' or by matching a list of regular expressions against the visit URL. #' @param wt webtrack data object. #' @param classes a data.table containing classes that can be matched to visits. #' @param match_by character. Whether to match list entries from `classes` to #' the domain of a visit (`"domain"`) or the host (`"host"`) with an exact match; #' or with a regular expression against the whole URL of a visit (`"regex"`). #' If set to `"domain"` or `"host"`, both `wt` and `classes` need to have #' a column called accordingly. If set to `"regex"`, the `url` column of `wt` #' will be used, and you need to set `regex_on` to the column in `classes` #' for which to do the pattern matching. Defaults to `"domain"`. #' @param regex_on character. Column in `classes` which to use for #' pattern matching. Defaults to `NULL`. #' @param return_rows_by character. A column in `classes` on which to #' subset the returning data. Defaults to `NULL`. #' @param return_rows_val character. The value of the columns specified in #' `return_rows_by`, for which data should be returned. For example, if your #' `classes` data contains a column `type`, which has a value called `"shopping"`, #' setting `return_rows_by` to `"type"` and `return_rows_val` to `"shopping"` #' will only return visits classified as `"shopping"`. #' @importFrom data.table is.data.table setnames #' @return webtrack data.table with the same columns as `wt` and any column #' in `classes` except the column specified by `match_by`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' data("domain_list") #' wt <- as.wt_dt(testdt_tracking) #' # classify visits via domain #' wt_domains <- extract_domain(wt, drop_na = FALSE) #' wt_classes <- classify_visits(wt_domains, classes = domain_list, match_by = "domain") #' # classify visits via domain #' # for the example, just renaming "domain" column #' domain_list$host <- domain_list$domain #' wt_hosts <- extract_host(wt, drop_na = FALSE) #' wt_classes <- classify_visits(wt_hosts, classes = domain_list, match_by = "host") #' # classify visits with pattern matching #' # for the example, any value in "domain" treated as pattern #' data("domain_list") #' regex_list <- domain_list[type == "facebook"] #' wt_classes <- classify_visits(wt[1:5000], #' classes = regex_list, #' match_by = "regex", regex_on = "domain" #' ) #' # classify visits via domain and only return class "search" #' data("domain_list") #' wt_classes <- classify_visits(wt_domains, #' classes = domain_list, #' match_by = "domain", return_rows_by = "type", #' return_rows_val = "search" #' ) #' } #' @export classify_visits <- function(wt, classes, match_by = "domain", regex_on = NULL, return_rows_by = NULL, return_rows_val = NULL) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) if (!is.data.table(classes)) { stop("classes needs to be a data.table") } match.arg(match_by, c("domain", "host", "regex")) if (match_by == "domain") { vars_exist(wt, vars = c("domain")) stopifnot("couldn't find the column 'domain' in the classes data" = "domain" %in% names(classes)) wt <- classes[wt, on = "domain"] } else if (match_by == "host") { vars_exist(wt, vars = c("host")) stopifnot("couldn't find the column 'host' in the classes data" = "host" %in% names(classes)) wt <- classes[wt, on = "host"] } else if (match_by == "regex") { stopifnot("You have to specify regex_on if match_by is set to 'regex'" = !is.null(regex_on)) vars_exist(wt, vars = c("url")) stopifnot("couldn't find the column set in 'regex_on' in the classes data" = regex_on %in% names(classes)) wt <- drop_query(wt) wt <- wt[, tmp_index := seq_len(.N)] tmp_wt <- wt[, list(tmp_index, url_noquery)] pattern <- paste(classes[[regex_on]], collapse = "|") tmp_wt_matched <- tmp_wt[grepl(pattern, url_noquery)] tmp_wt_matched <- tmp_wt_matched[, match := regmatches(url_noquery, regexpr(pattern, url_noquery))] wt_matched <- tmp_wt_matched[, url_noquery := NULL][wt, on = "tmp_index"] setnames(wt_matched, "match", regex_on) wt <- classes[wt_matched, on = regex_on][, c("url_noquery", "tmp_index") := NULL] } if (!is.null(return_rows_by)) { vars_exist(classes, vars = return_rows_by) stopifnot("You have to specify return_rows_val if return_rows_by is not NULL" = !is.null(return_rows_val)) wt <- wt[get(return_rows_by) == return_rows_val] } class(wt) <- c("wt_dt", class(wt)) wt[] }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/classify.R
#' Test data #' #' Sample of fully anomymized webtrack data from a research project with US participants "testdt_tracking" #' Test survey #' #' Randomly generated survey data only used for illustrative purposes (wide format) "testdt_survey_w" #' Test survey #' #' Same randomly generated survey data, one row per person/wave (long format) "testdt_survey_l" #' News Types #' #' Classification of domains into different news types #' @references #' Stier, S., Mangold, F., Scharkow, M., & Breuer, J. (2022). Post Post-Broadcast Democracy? News Exposure in the Age of Online Intermediaries. American Political Science Review, 116(2), 768-774. "news_types" #' Domain list #' classification of domains into news,portals, search, and social media #' @references #' Stier, S., Mangold, F., Scharkow, M., & Breuer, J. (2022). Post Post-Broadcast Democracy? News Exposure in the Age of Online Intermediaries. American Political Science Review, 116(2), 768-774. "domain_list" #' Bakshy Top500 #' Ideological alignment of 500 domains based on facebook data #' @references Bakshy, Eytan, Solomon Messing, and Lada A. Adamic. "Exposure to ideologically diverse news and opinion on Facebook." Science 348.6239 (2015): 1130-1132. "bakshy"
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/data.R
utils::globalVariables(c( "duration", "timestamp", "panelist_id", "domain", "visit", "day", "type", "prev_type", "tmp", "session", "path", "host", "suffix", "domain_name", "url_next", "host_next", "domain_next", "url_previous", "host_previous", "domain_previous", "date", "week", "month", "year", "wave", "duplicate", "i.type", "title", "visits", "url_noquery", "referral", "tmp_timestamp_next", "tmp_url_next", "tmp_host", "tmp_suffix", "tmp_path", "tmp_scheme", "tmp_domain_name", "tmp_index", "tmp_class", "tmp_duration", "tmp_timeframe", "tmp_visits", "tmp_last", "device", "device_next", "tmp_timestamp_prev", "tmp_url_prev", "tmp_index" ))
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/globals.R
#' Isolation Index #' @description Given two groups (A and B) of individuals, the isolation index captures the #' extent to which group A disproportionately visit websites whose other visitors #' are also members of group A. #' @param grp_A vector (usually corresponds to a column in a webtrack #' data.table) indicating the number of individuals of group A using a website #' @param grp_B vector (usually corresponds to a column in a webtrack #' data.table) indicating the number of individuals of group B using a website #' @details a value of 1 indicates that the websites visited by group A and group B do not overlap. #' A value of 0 means both visit exactly the same websites #' @return numeric value between 0 and 1. 0 indicates no isolation and 1 perfect isolation #' @references #' Cutler, David M., Edward L. Glaeser, and Jacob L. Vigdor. "The rise and decline of the American ghetto." Journal of political economy 107.3 (1999): 455-506. #' Gentzkow, Matthew, and Jesse M. Shapiro. "Ideological segregation online and offline." The Quarterly Journal of Economics 126.4 (2011): 1799-1839. #' @examples #' # perfect isolation #' left <- c(5, 5, 0, 0) #' right <- c(0, 0, 5, 5) #' isolation_index(left, right) #' #' # perfect overlap #' left <- c(5, 5, 5, 5) #' right <- c(5, 5, 5, 5) #' isolation_index(left, right) #' @export isolation_index <- function(grp_A, grp_B) { if (length(grp_A) != length(grp_B)) { stop("grp_A and grp_B need to have the same length") } grp_A <- grp_A / sum(grp_A, na.rm = TRUE) grp_B <- grp_B / sum(grp_B, na.rm = TRUE) right_share <- grp_B / (grp_A + grp_B) bilanz <- (grp_B - grp_A) * right_share sum(bilanz, na.rm = TRUE) } # Will be incorporated later # dissimilarity_index <- function(left,right){ # if(length(left)!=length(right)){ # stop("left and right need to have the same length") # } # left <- left/sum(left,na.rm = TRUE) # right <- right/sum(right,na.rm = TRUE) # bilanz <- abs(right - left) # 0.5 * sum(bilanz,na.rm = TRUE) # } # # atkinson <- function(left,right){ # if(length(left)!=length(right)){ # stop("left and right need to have the same length") # } # left <- (left/sum(left,na.rm = TRUE))^(1/2) # right <- (right/sum(right,na.rm = TRUE))^(1/2) # bilanz <- left * right # 1 - sum(bilanz, na.rm = TRUE) # }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/indices.R
#' Add time spent on a visit in seconds #' @description #' `add_duration()` approximates the time spent on a visit based on the difference #' between two consecutive timestamps, replacing differences exceeding `cutoff` with #' the value defined in `replace_by`. #' @param wt webtrack data object. #' @param cutoff numeric (seconds). If duration is greater than this value, #' it is reset to the value defined by `replace_by`. Defaults to 300 seconds. #' @param replace_by numeric. Determines whether differences greater than #' the cutoff are set to `NA`, or some value. Defaults to `NA`. #' @param last_replace_by numeric. Determines whether the last visit #' for an individual is set to `NA`, or some value. Defaults to `NA`. #' @param device_switch_na boolean. Relevant only when data was collected #' from multiple devices. When visits are ordered by timestamp sequence, #' two consecutive visits can come from different devices, which makes the #' timestamp difference less likely to be the true duration. It may be #' preferable to set the duration of the visit to `NA` (`TRUE`) rather than #' the difference to the next timestamp (`FALSE`). Defaults to `FALSE`. #' @param device_var character. Column indicating device. #' Required if 'device_switch_na' set to `TRUE`. Defaults to `NULL`. #' @importFrom data.table is.data.table shift setorder setnames #' @return webtrack data.table (ordered by panelist_id and timestamp) with #' the same columns as wt and a new column called `duration`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- add_duration(wt) #' # Defining cutoff at 10 minutes, replacing those exceeding cutoff to 5 minutes, #' # and setting duration before device switch to `NA`: #' wt <- add_duration(wt, #' cutoff = 600, replace_by = 300, #' device_switch_na = TRUE, device_var = "device" #' ) #' } #' @export add_duration <- function(wt, cutoff = 300, replace_by = NA, last_replace_by = NA, device_switch_na = FALSE, device_var = NULL) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) stopifnot("replace_by must be NA or greater/equal zero" = (is.na(replace_by) | replace_by > 0)) if (device_switch_na == TRUE) { stopifnot("'device_var' must be specified if device_switch_na = TRUE" = !is.null(device_var)) } vars_exist(wt, vars = c("panelist_id", "timestamp", device_var)) setorder(wt, panelist_id, timestamp) wt[, duration := as.numeric(shift(timestamp, n = 1, type = "lead", fill = NA) - timestamp), by = "panelist_id"] wt[, tmp_last := ifelse(is.na(duration), T, F)] if (device_switch_na == T) { setnames(wt, device_var, "device") wt[, device_next := shift(device, n = 1, type = "lead", fill = NA), by = "panelist_id"] wt[tmp_last == T, duration := last_replace_by] wt[duration > cutoff & tmp_last == F, duration := replace_by] wt[device_next != device & tmp_last == F, duration := NA] setnames(wt, "device", device_var) wt[, device_next := NULL] } else { wt[tmp_last == T, duration := last_replace_by] wt[duration > cutoff & tmp_last == F, duration := replace_by] } wt[, tmp_last := NULL] wt[] } #' Add a session variable #' @description #' `add_session()` groups visits into "sessions", defining a session to end #' when the difference between two consecutive timestamps exceeds a `cutoff`. #' @param wt webtrack data object. #' @param cutoff numeric (seconds). If the difference between two consecutive #' timestamps exceeds this value, a new browsing session is defined. #' @importFrom data.table is.data.table shift setorder setnafill .N #' @return webtrack data.table (ordered by panelist_id and timestamp) #' with the same columns as wt and a new column called `session`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Setting cutoff to 30 minutes #' wt <- add_session(wt, cutoff = 1800) #' } #' @export add_session <- function(wt, cutoff) { stopifnot("'cutoff' argument is missing" = !missing(cutoff)) stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", "timestamp")) setorder(wt, panelist_id, timestamp) wt[, tmp_index := 1:.N, by = panelist_id] wt[as.numeric(shift(timestamp, n = 1, type = "lead", fill = NA) - timestamp) > cutoff, session := 1:.N, by = "panelist_id"] wt[, session := ifelse(tmp_index == 1, 1, session)] setnafill(wt, type = "locf", cols = "session") wt[, tmp_index := NULL] wt[] } #' Deduplicate visits #' @description #' `deduplicate()` flags, drops or aggregates duplicates, which are defined as #' consecutive visits to the same URL within a certain time frame. #' @param wt webtrack data object. #' @param method character. One of `"aggregate"`, `"flag"` or `"drop"`. #' If set to `"aggregate"`, consecutive visits (no matter the time difference) #' to the same URL are combined and their duration aggregated. #' In this case, a duration column must be specified via `"duration_var"`. #' If set to `"flag"`, duplicates within a certain time frame are flagged in a new #' column called `duplicate`. In this case, `within` argument must be specified. #' If set to `"drop"`, duplicates are dropped. Again, `within` argument must be specified. #' Defaults to `"aggregate"`. #' @param within numeric (seconds). If `method` set to `"flag"` or `"drop"`, #' a subsequent visit is only defined as a duplicate when happening within #' this time difference. Defaults to 1 second. #' @param duration_var character. Name of duration variable. Defaults to `"duration"`. #' @param keep_nvisits boolean. If method set to `"aggregate"`, this determines whether #' number of aggregated visits should be kept as variable. Defaults to `FALSE`. #' @param same_day boolean. If method set to `"aggregate"`, determines #' whether to count visits as consecutive only when on the same day. Defaults to `TRUE`. #' @importFrom data.table is.data.table shift .N setnames setorder #' @return webtrack data.table with the same columns as wt with updated duration #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- add_duration(wt, cutoff = 300, replace_by = 300) #' # Dropping duplicates with one-second default #' wt_dedup <- deduplicate(wt, method = "drop") #' # Flagging duplicates with one-second default #' wt_dedup <- deduplicate(wt, method = "flag") #' # Aggregating duplicates #' wt_dedup <- deduplicate(wt[1:1000], method = "aggregate") #' # Aggregating duplicates and keeping number of visits for aggregated visits #' wt_dedup <- deduplicate(wt[1:1000], method = "aggregate", keep_nvisits = TRUE) #' } #' @export deduplicate <- function(wt, method = "aggregate", within = 1, duration_var = "duration", keep_nvisits = FALSE, same_day = TRUE) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("url", "panelist_id", "timestamp")) setorder(wt, panelist_id, timestamp) if (method == "aggregate") { vars_exist(wt, vars = duration_var) setnames(wt, duration_var, "duration") wt[, visit := cumsum(url != shift(url, n = 1, type = "lag", fill = 0)), by = "panelist_id"] if (same_day == TRUE) { wt[, day := as.Date(timestamp)] grp_vars <- c("panelist_id", "visit", "url", "day") wt <- wt[, list( visits = .N, duration = sum(as.numeric(duration), na.rm = TRUE), timestamp = min(timestamp) ), by = grp_vars] wt[, day := NULL] } else { grp_vars <- c("panelist_id", "visit", "url") wt <- wt[, list( visits = .N, duration = sum(as.numeric(duration), na.rm = TRUE), timestamp = min(timestamp) ), by = grp_vars] } wt[, visit := NULL] if (keep_nvisits == FALSE) { wt[, visits := NULL] } setnames(wt, "duration", duration_var) } else if (method %in% c("drop", "flag")) { stopifnot("'within' must be specified if 'method' set to 'flag' or 'drop" = !is.null(within)) wt[, tmp_timestamp_prev := shift(timestamp, n = 1, type = "lag", fill = NA), by = "panelist_id"] wt[, tmp_url_prev := shift(url, n = 1, type = "lag", fill = NA), by = "panelist_id"] wt[, duplicate := ifelse(is.na(tmp_url_prev), FALSE, ifelse( (timestamp - tmp_timestamp_prev <= within) & (url == tmp_url_prev), TRUE, FALSE )), by = "panelist_id" ] if (method == "drop") { wt <- wt[duplicate == FALSE] wt[, duplicate := NULL] } wt[, tmp_url_prev := NULL] wt[, tmp_timestamp_prev := NULL] } wt[] } #' Extract the host from URL #' @description #' `extract_host()` adds the host of a URL as a new column. #' The host is defined as the part following the scheme (e.g., "https://") and #' preceding the subdirectory (anything following the next "/"). Note that #' for URL entries like `chrome-extension://soomething` or `http://192.168.0.1/something`, #' result will be set to `NA`. #' @param wt webtrack data object. #' @param varname character. Name of the column from which to extract the host. #' Defaults to `"url"`. #' @param drop_na boolean. Determines whether rows for which no host can be extracted #' should be dropped from the data. Defaults to `TRUE`. #' @importFrom data.table is.data.table fifelse #' @return webtrack data.table with the same columns as wt #' and a new column called `'host'` (or, if varname not equal to `'url'`, `'<varname>_host'`) #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Extract host and drop rows without host #' wt <- extract_host(wt) #' # Extract host and keep rows without host #' wt <- extract_host(wt, drop_na = FALSE) #' } #' @export extract_host <- function(wt, varname = "url", drop_na = TRUE) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = varname) wt[, tmp_host := urltools::domain(gsub("@", "%40", get(varname)))] wt[, tmp_suffix := urltools::suffix_extract(tmp_host)[["suffix"]]] if (varname == "url") { wt[, host := fifelse(is.na(tmp_suffix), NA_character_, urltools::domain(tmp_host))] n_na <- nrow(wt[is.na(host)]) if (drop_na == TRUE) { wt <- wt[!is.na(host)] if (n_na > 0) { warning(paste0("Host could not be extracted for ", n_na, " rows, which were dropped from the data. Set drop_na = FALSE to keep these rows.")) } } else { if (n_na > 0) { warning(paste0("Host could not be extracted for ", n_na, " rows. Set drop_na = TRUE to drop these rows.")) } } } else { wt[, paste0(varname, "_host") := fifelse(is.na(tmp_suffix), NA_character_, urltools::domain(tmp_host))] n_na <- nrow(wt[is.na(paste0(varname, "_host"))]) if (drop_na == TRUE) { wt <- wt[!is.na(paste0(varname, "_host"))] if (n_na > 0) { warning(paste0("Host could not be extracted for ", n_na, " rows, which were dropped from the data. Set drop_na = FALSE to keep these rows.")) } } else { if (n_na > 0) { warning(paste0("Host could not be extracted for ", n_na, " rows. Set drop_na = TRUE to drop these rows.")) } } } wt[, tmp_host := NULL] wt[] } #' Extract the domain from URL #' @description #' `extract_domain()` adds the domain of a URL as a new column. #' By "domain", we mean the "top private domain", i.e., the domain under #' the public suffix (e.g., "`com`") as defined by the Public Suffix List. #' See details. #' @details #' We define a "web domain" in the common colloquial meaning, that is, #' the part of an web address that identifies the person or organization in control. #' is `google.com`. More technically, what we mean by "domain" is the #' "top private domain", i.e., the domain under the public suffix, #' as defined by the Public Suffix List. #' Note that this definition sometimes leads to counterintuitive results because #' not all public suffixes are "registry suffixes". That is, they are not controlled #' by a domain name registrar, but allow users to directly register a domain. #' One example of such a public, non-registry suffix is `blogspot.com`. For a URL like #' `www.mysite.blogspot.com`, our function, and indeed the packages we are aware of, #' would extract the domain as `mysite.blogspot.com`, although you might think of #' `blogspot.com` as the domain. #' For details, see [here](https://github.com/google/guava/wiki/InternetDomainNameExplained) #' @param wt webtrack data object. #' @param varname character. Name of the column from which to extract the host. #' Defaults to `"url"`. #' @param drop_na boolean. Determines whether rows for which no host can be extracted #' should be dropped from the data. Defaults to `TRUE`. #' @description Extracts the domain from urls. #' @importFrom data.table is.data.table fcase #' @return webtrack data.table with the same columns as wt #' and a new column called `'domain'` #' (or, if varname not equal to `'url'`, `'<varname>_domain'`) #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Extract domain and drop rows without domain #' wt <- extract_domain(wt) #' # Extract domain and keep rows without domain #' wt <- extract_domain(wt, drop_na = FALSE) #' } #' @export extract_domain <- function(wt, varname = "url", drop_na = TRUE) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = varname) wt[, tmp_host := urltools::domain(gsub("@", "%40", get(varname)))] wt[, tmp_suffix := urltools::suffix_extract(tmp_host)[["suffix"]]] wt[, tmp_domain_name := urltools::suffix_extract(tmp_host)[["domain"]]] if (varname == "url") { wt[, domain := ifelse((!is.na(tmp_suffix)), paste0(tmp_domain_name, ".", tmp_suffix), NA)] } else { wt[, paste0(varname, "_domain") := ifelse((!is.na(tmp_suffix)), paste0(tmp_domain_name, ".", tmp_suffix), NA)] } if (varname == "url") { wt[, domain := fcase( is.na(tmp_suffix), NA_character_, !is.na(tmp_suffix) & is.na(tmp_domain_name), tmp_suffix, !is.na(tmp_suffix) & !is.na(tmp_domain_name), paste0(tmp_domain_name, ".", tmp_suffix) )] n_na <- nrow(wt[is.na(domain)]) } else { wt[, paste0(varname, "_domain") := fcase( is.na(tmp_suffix), NA_character_, !is.na(tmp_suffix) & is.na(tmp_domain_name), tmp_suffix, !is.na(tmp_suffix) & !is.na(tmp_domain_name), paste0(tmp_domain_name, ".", tmp_suffix) )] n_na <- nrow(wt[is.na(paste0(varname, "_domain"))]) } wt[, tmp_host := NULL] wt[, tmp_suffix := NULL] wt[, tmp_domain_name := NULL] if (drop_na == TRUE) { if (varname == "url") { wt <- wt[!is.na(domain)] } else { wt <- wt[!is.na(paste0(varname, "_domain"))] } if (n_na > 0) { warning(paste0("Domain could not be extracted for ", n_na, " rows, which were dropped from the data. Set drop_na = FALSE to keep these rows.")) } } else { if (n_na > 0) { warning(paste0("Domain could not be extracted for ", n_na, " rows. Set drop_na = TRUE to drop these rows.")) } } wt[] } #' Extract the path from URL #' @description #' `extract_path()` adds the path of a URL as a new column. #' The path is defined as the part following the host but not including a #' query (anything after a "?") or a fragment (anything after a "#"). #' @param wt webtrack data object #' @param varname character. name of the column from which to extract the host. #' Defaults to `"url"`. #' @importFrom data.table is.data.table #' @return webtrack data.table with the same columns as wt #' and a new column called `'path'` (or, if varname not equal to `'url'`, `'<varname>_path'`) #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Extract path #' wt <- extract_path(wt) #' } #' @export extract_path <- function(wt, varname = "url") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = varname) wt[, tmp_host := urltools::domain(gsub("@", "%40", get(varname)))] wt[, tmp_path := urltools::path(gsub("@", "%40", get(varname)))] if (varname == "url") { wt[, path := gsub("%40", "@", tmp_path)] } else { wt[, paste0(varname, "_path") := gsub("%40", "@", tmp_path)] } wt[, tmp_host := NULL] wt[, tmp_path := NULL] wt[] } #' Drop the query and fragment from URL #' @description #' `drop_query()` adds the URL without query and fragment as a new column. #' The query is defined as the part following a "?" after the path. #' The fragement is anything following a "#" after the query. #' @param wt webtrack data object. #' @param varname character. name of the column from which to extract the host. #' Defaults to `"url"`. #' @importFrom data.table is.data.table %like% #' @return webtrack data.table with the same columns as wt #' and a new column called `'<varname>_noquery'` #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Extract URL without query/fragment #' wt <- drop_query(wt) #' } #' @export drop_query <- function(wt, varname = "url") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = varname) wt[, tmp_host := urltools::domain(gsub("@", "%40", get(varname)))] wt[, tmp_path := urltools::path(gsub("@", "%40", get(varname)))] wt[, tmp_path := gsub("%40", "@", tmp_path)] wt[, tmp_scheme := urltools::scheme(get(varname))] wt[is.na(tmp_host), tmp_host := ""] wt[is.na(tmp_path), tmp_path := ""] wt[is.na(tmp_scheme), tmp_scheme := ""] wt[, paste0(varname, "_noquery") := paste0(tmp_scheme, "://", tmp_host, "/", tmp_path, recycle0 = T)] wt[, tmp_host := NULL] wt[, tmp_path := NULL] wt[, tmp_scheme := NULL] wt[] } #' Add the next visit as a new column #' @description #' `add_next_visit()` adds the subsequent visit, as determined by order of #' timestamps as a new column. The next visit can be added as either the full URL, #' the extracted host or the extracted domain, depending on `level`. #' @param wt webtrack data object. #' @param level character. Either `"url"`, `"host"` or `"domain"`. Defaults to `"url"`. #' @importFrom data.table is.data.table shift setorder #' @return webtrack data.table with the same columns as wt and #' a new column called `url_next`,`host_next` or `domain_next`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Adding next full URL as new column #' wt <- add_next_visit(wt, level = "url") #' # Adding next host as new column #' wt <- add_next_visit(wt, level = "host") #' # Adding next domain as new column #' wt <- add_next_visit(wt, level = "domain") #' } #' @export add_next_visit <- function(wt, level = "url") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", "timestamp")) setorder(wt, panelist_id, timestamp) if (level == "url") { wt[, url_next := shift(url, n = 1, type = "lead", fill = NA), by = "panelist_id"] } else if (level == "host") { if (!"host" %in% names(wt)) { suppressWarnings(wt <- extract_host(wt, varname = "url", drop_na = F)) wt[, host_next := shift(host, n = 1, type = "lead", fill = NA), by = "panelist_id"] wt[, host := NULL] } else { wt[, host_next := shift(host, n = 1, type = "lead", fill = NA), by = "panelist_id"] } } else if (level == "domain") { if (!"domain" %in% names(wt)) { suppressWarnings(wt <- extract_domain(wt, varname = "url", drop_na = F)) wt[, domain_next := shift(domain, n = 1, type = "lag", fill = NA), by = "panelist_id"] wt[, domain := NULL] } else { wt[, domain_next := shift(domain, n = 1, type = "lag", fill = NA), by = "panelist_id"] } } wt[] } #' Add the previous visit as a new column #' @description #' `add_previous_visit()` adds the previous visit, as determined by order of #' timestamps as a new column The previous visit can be added as either the full URL, #' the extracted host or the extracted domain, depending on `level`. #' @param wt webtrack data object. #' @param level character. Either `"url"`, `"host"` or `"domain"`. Defaults to `"url"`. #' @importFrom data.table is.data.table shift setorder #' @return webtrack data.table with the same columns as wt and #' a new column called `url_previous`,`host_previous` or `domain_previous.`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # Adding previous full URL as new column #' wt <- add_previous_visit(wt, level = "url") #' # Adding previous host as new column #' wt <- add_previous_visit(wt, level = "host") #' # Adding previous domain as new column #' wt <- add_previous_visit(wt, level = "domain") #' } #' @export add_previous_visit <- function(wt, level = "url") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", "timestamp")) setorder(wt, panelist_id, timestamp) if (level == "url") { wt[, url_previous := shift(url, n = 1, type = "lag", fill = NA), by = "panelist_id"] } else if (level == "host") { if (!"host" %in% names(wt)) { suppressWarnings(wt <- extract_host(wt, varname = "url", drop_na = F)) wt[, host_previous := shift(host, n = 1, type = "lag", fill = NA), by = "panelist_id"] wt[, host := NULL] } else { wt[, host_previous := shift(host, n = 1, type = "lag", fill = NA), by = "panelist_id"] } } else if (level == "domain") { if (!"domain" %in% names(wt)) { suppressWarnings(wt <- extract_domain(wt, varname = "url", drop_na = F)) wt[, domain_previous := shift(domain, n = 1, type = "lag", fill = NA), by = "panelist_id"] wt[, domain := NULL] } else { wt[, domain_previous := shift(domain, n = 1, type = "lag", fill = NA), by = "panelist_id"] } } wt[] } #' Download and add the "title" of a URL #' @description #' `add_title()` gets the title of a URL by accessing the web address online #' and adds the title as a new column. See details for the meaning of "title". #' You need an internet connection to run this function. #' @details The title of a website (the text within the `<title>` tag #' of a web site's `<head>`) #' is the text that is shown on the "tab" #' when looking at the website in a browser. It can contain useful information #' about a URL's content and can be used, for example, for classification purposes. #' Note that it may take a while to run this function for a large number of URLs. #' @param wt webtrack data object. #' @param lang character (a language tag). Language accepted by the request. #' Defaults to `"en-US,en-GB,en"`. Note that you are likely to still obtain titles #' different from the ones seen originally by the user, because the language #' also depend on the user's IP and device settings. #' @importFrom data.table is.data.table #' @importFrom rvest html_text html_node read_html #' @importFrom httr GET add_headers #' @return webtrack data.table with the same columns as wt and a new column #' called `"title"`, which will be `NA` if the title cannot be retrieved. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking)[1:2] #' # Get titles with `lang` set to default English #' wt_titles <- add_title(wt) #' # Get titles with `lang` set to German #' wt_titles <- add_title(wt, lang = "de") #' } #' @export add_title <- function(wt, lang = "en-US,en-GB,en") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", "url")) urls <- data.table(url = unique(wt$url)) urls[, title := mapply(function(x) { return( tryCatch( html_text(html_node( read_html( GET(x, add_headers(.headers = c( "user_agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246", "Accept-language" = lang ))) ), "head title" )), error = function(e) NA ) ) }, url)] closeAllConnections() wt <- wt[urls, on = "url"] wt[] } #' Add social media referrals as a new column #' @description #' Identifies whether a visit was referred to from social media and #' adds it as a new column. See details for method. #' @details To identify referrals, we rely on the method described as most valid #' in Schmidt et al.: When the domain preceding a visit was to the platform in question, #' and the query string of the visit's URL contains a certain pattern, #' we count it as a referred visit. For Facebook, the pattern has been identified #' by Schmidt et al. as `'fbclid='`, although this can change in future. #' @param wt webtrack data object. #' @param platform_domains character. A vector of platform domains for which #' referrers should be identified. Order and length must correspondent to `patterns` argument #' @param patterns character. A vector of patterns for which referrers should #' be identified. Order and length must correspondent to `platform_domains` vector. #' @importFrom data.table is.data.table #' @return webtrack data.table with the same columns as wt and a new column called `referral`, #' which takes on NA if no referral has been identified, or the name specified #' platform_domains if a referral from that platform has been identified #' @references #' Schmidt, Felix, Frank Mangold, Sebastian Stier and Roberto Ulloa. "Facebook as an Avenue to News: A Comparison and Validation of Approaches to Identify Facebook Referrals". Working paper. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- add_referral(wt, platform_domains = "facebook.com", patterns = "fbclid=") #' wt <- add_referral(wt, #' platform_domains = c("facebook.com", "twitter.com"), #' patterns = c("fbclid=", "utm_source=twitter") #' ) #' } #' @export add_referral <- function(wt, platform_domains, patterns) { stopifnot("Input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("panelist_id", "url", "timestamp")) stopifnot("Number of platform_domains must be identical to number of patterns" = length(platform_domains) == length(patterns)) wt <- add_previous_visit(wt, level = "domain") wt[, referral := NA] for (i in seq_along(platform_domains)) { wt[, referral := ifelse(grepl(patterns[i], url) & domain_previous == platform_domains[i] & is.na(referral), platform_domains[i], referral)] } wt[, domain_previous := NULL] wt[] } #' Create an urldummy variable from a data.table object #' @param wt webtrack data object #' @param dummy a vector of urls that should be dummy coded #' @param name name of dummy variable to create. #' @importFrom data.table setnames setattr #' @return webtrack object with the same columns and a new column called "name" including the dummy variable #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' wt <- extract_domain(wt) #' code_urls <- "https://dkr1.ssisurveys.com/tzktsxomta" #' create_urldummy(wt, dummy = code_urls, name = "test_dummy") #' } #' @export create_urldummy <- function(wt, dummy, name) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c("url")) wt[, dummy := data.table::fifelse(url %in% dummy, TRUE, FALSE)] setnames(wt, "dummy", name) setattr(wt, "dummy", c(attr(wt, "dummy"), name)) wt[] } #' Add panelist features to tracking data #' @description #' `add_panelist_data()` adds information about panelists (e.g., from a survey) #' to the tracking data. #' @param wt webtrack data object. #' @param data a data.table (or object that can be converted to data.table) #' which contains columns about panelists #' @param cols character vector of columns to add. If `NULL`, all columns are added. #' Defaults to `NULL`. #' @param join_on which columns to join on. Defaults to `"panelist_id"`. #' @importFrom data.table is.data.table as.data.table setattr #' @return webtrack object with the same columns and the columns from `data` #' specified in `cols`. #' @examples #' \dontrun{ #' data("testdt_tracking") #' data("testdt_survey_w") #' wt <- as.wt_dt(testdt_tracking) #' # add survey test data #' add_panelist_data(wt, testdt_survey_w) #' } #' @export add_panelist_data <- function(wt, data, cols = NULL, join_on = "panelist_id") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) vars_exist(wt, vars = c(join_on)) if (!is.data.table(data)) { data <- as.data.table(data) } vars_exist(data, vars = c(join_on)) if (!is.null(cols)) { if (!all(cols %in% names(data))) { stop("couldn't locate all columns in data") } data <- data[, c(join_on, cols), with = FALSE] setattr(wt, "panelist", cols) } else { setattr(wt, "panelist", setdiff(names(data), join_on)) } data <- data[wt, on = join_on] class(data) <- c("wt_dt", class(data)) data }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/preprocess.R
#' Summarize number of visits by person #' @description #' `sum_visits()` summarizes the number of visits by person within a `timeframe`, #' and optionally by `visit_class` of visit. #' @param wt webtrack data object. #' @param timeframe character. Indicates for what time frame to aggregate visits. #' Possible values are `"date"`, `"week"`, `"month"`, `"year"`, `"wave"` or `NULL`. #' If set to `"wave"`, `wt` must contain a column call `wave`. Defaults to `NULL`, #' in which case the output contains number of visits for the entire time. #' @param visit_class character. Column that contains a classification of visits. #' For each value in this column, the output will have a column indicating the #' number of visits belonging to that value. Defaults to `NULL`. #' @importFrom data.table is.data.table shift .N dcast setnames #' @return a data.table with columns `panelist_id`, column indicating the time unit #' (unless `timeframe` set to `NULL`), `n_visits` indicating the number of visits, #' and a column for each value of `visit_class`, if specified. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # summarize for whole period #' wt_summ <- sum_visits(wt) #' # summarize by week #' wt_summ <- sum_visits(wt, timeframe = "week") #' # create a class variable to summarize by class #' wt <- suppressWarnings(extract_domain(wt, drop_na = TRUE)) #' wt[, google := ifelse(domain == "google.com", 1, 0)] #' wt_summ <- sum_visits(wt, timeframe = "week", visit_class = "google") #' } #' @export sum_visits <- function(wt, timeframe = NULL, visit_class = NULL) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) match.arg(timeframe, c(NULL, "date", "week", "month", "year", "wave")) vars_exist(wt, vars = c("url", "panelist_id", "timestamp")) if (!is.null(timeframe)) { if (timeframe == "date") { wt[, `:=`(date = format(timestamp, format = "%F"))] } else if (timeframe == "week") { wt[, `:=`(week = format(timestamp, format = "%Y week %W"))] } else if (timeframe == "month") { wt[, `:=`(month = format(timestamp, format = "%Y month %m"))] } else if (timeframe == "year") { wt[, `:=`(year = format(timestamp, format = "%Y"))] } else if (timeframe == "wave") { stopifnot("couldn't find the column 'wave' in the webtrack data" = "wave" %in% names(wt)) } } grp_vars <- c("panelist_id", timeframe) summary <- wt[, list("n_visits" = .N), by = grp_vars] if (!is.null(visit_class)) { wt <- wt[, tmp_class := paste0("n_visits_", visit_class, "_", get(visit_class))] grp_vars <- c("panelist_id", timeframe, "tmp_class") tmp_summary <- wt[, list("tmp_visits" = .N), by = grp_vars] if (is.null(timeframe)) { tmp_summary <- dcast(tmp_summary, panelist_id ~ tmp_class, value.var = c("tmp_visits"), fill = 0) } else { setnames(tmp_summary, timeframe, "tmp_timeframe") tmp_summary <- dcast(tmp_summary, panelist_id + tmp_timeframe ~ tmp_class, value.var = c("tmp_visits"), fill = 0) setnames(tmp_summary, "tmp_timeframe", timeframe) } wt[, tmp_class := NULL] summary <- summary[tmp_summary, on = c("panelist_id", timeframe)] } if (!is.null(timeframe)) { wt[[timeframe]] <- NULL } summary[] } #' Summarize visit duration by person #' @description #' `sum_durations()` summarizes the duration of visits by person within a `timeframe`, #' and optionally by `visit_class` of visit. Note: #' - If for a time frame all rows are NA on the duration column, the summarized duration for that time frame will be NA. #' - If only some of the rows of a time frame are NA on the duration column, the function will ignore those NA rows. #' - If there were no visits to a class (i.e., a value of the 'visit_class' column) for a time frame, the summarized duration for that time frame will be zero; if there were visits, but NA on duration, the summarized duration will be NA. #' @param wt webtrack data object. #' @param var_duration character. Name of the duration variable if already present. #' Defaults to `NULL`, in which case duration will be approximated with #' `add_duration(wt, cutoff = 300, replace_by = "na", replace_val = NULL)` #' @param timeframe character. Indicates for what time frame to aggregate visit durations. #' Possible values are `"date"`, `"week"`, `"month"`, `"year"`, `"wave"` or `NULL`. #' If set to `"wave"`, `wt` must contain a column call `wave`. Defaults to `NULL`, #' in which case the output contains duration of visits for the entire time. #' @param visit_class character. Column that contains a classification of visits. #' For each value in this column, the output will have a column indicating the #' number of visits belonging to that value. Defaults to `NULL`. #' @importFrom data.table is.data.table shift .N dcast setnames #' @return a data.table with columns `panelist_id`, column indicating the time unit #' (unless `timeframe` set to `NULL`), `duration_visits` indicating the duration of visits #' (in seconds, or whatever the unit of the variable specified by `var_duration` parameter), #' and a column for each value of `visit_class`, if specified. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # summarize for whole period #' wt_summ <- sum_durations(wt) #' # summarize by week #' wt_summ <- sum_durations(wt, timeframe = "week") #' # create a class variable to summarize by class #' wt <- suppressWarnings(extract_domain(wt, drop_na = TRUE)) #' wt[, google := ifelse(domain == "google.com", 1, 0)] #' wt_summ <- sum_durations(wt, timeframe = "week", visit_class = "google") #' } #' @export sum_durations <- function(wt, var_duration = NULL, timeframe = NULL, visit_class = NULL) { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) match.arg(timeframe, c("date", "week", "month", "year", "wave", NULL)) vars_exist(wt, vars = c("url", "panelist_id", "timestamp")) if (is.null(var_duration)) { wt <- add_duration(wt) } else { vars_exist(wt, vars = c(var_duration)) colnames(wt)[colnames(wt) == var_duration] <- "duration" } if (!is.null(timeframe)) { if (timeframe == "date") { wt[, `:=`(date = format(timestamp, format = "%F"))] } else if (timeframe == "week") { wt[, `:=`(week = format(timestamp, format = "%Y week %W"))] } else if (timeframe == "month") { wt[, `:=`(month = format(timestamp, format = "%Y month %m"))] } else if (timeframe == "year") { wt[, `:=`(year = format(timestamp, format = "%Y"))] } else if (timeframe == "wave") { stopifnot("couldn't find the column 'wave' in the webtrack data" = "wave" %in% names(wt)) } } grp_vars <- c("panelist_id", timeframe) summary <- wt[, list("duration_visits" = if (all(is.na(duration))) NA_real_ else sum(duration, na.rm = TRUE)), by = grp_vars] if (!is.null(visit_class)) { wt <- wt[, tmp_class := paste0("duration_visits_", visit_class, "_", get(visit_class))] grp_vars <- c("panelist_id", timeframe, "tmp_class") tmp_summary <- wt[, list("tmp_duration" = if (all(is.na(duration))) NA_real_ else sum(duration, na.rm = TRUE)), by = grp_vars] if (is.null(timeframe)) { tmp_summary <- dcast(tmp_summary, panelist_id ~ tmp_class, value.var = c("tmp_duration"), fill = 0) } else { setnames(tmp_summary, timeframe, "tmp_timeframe") tmp_summary <- dcast(tmp_summary, panelist_id + tmp_timeframe ~ tmp_class, value.var = c("tmp_duration"), fill = 0) setnames(tmp_summary, "tmp_timeframe", timeframe) } wt[, tmp_class := NULL] summary <- summary[tmp_summary, on = c("panelist_id", timeframe)] } if (!is.null(timeframe)) { wt[[timeframe]] <- NULL } summary[] } #' Summarize activity per person #' @description #' `sum_activity()` counts the number of active time periods (i.e., days, weeks, #' months, years, or waves) by `panelist_id`. A period counts as "active" if #' the panelist provided at least one visit for that period. #' @param wt webtrack data object. #' @param timeframe character. Indicates for what time frame to aggregate visits. #' Possible values are `"date"`, `"week"`, `"month"`, `"year"` or `"wave"`. If #' set to `"wave"`, `wt` must contain a column call `wave`. Defaults to `"date"`. #' @importFrom data.table is.data.table shift .N #' @return a data.table with columns `panelist_id`, column indicating the #' number of active time units. #' @examples #' \dontrun{ #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' # summarize activity by day #' wt_sum <- sum_activity(wt, timeframe = "date") #' } #' @export sum_activity <- function(wt, timeframe = "date") { stopifnot("input is not a wt_dt object" = is.wt_dt(wt)) timeframe <- match.arg(timeframe, c("date", "week", "month", "year", "wave")) vars_exist(wt, vars = c("url", "panelist_id", "timestamp")) if (timeframe == "date") { wt[, `:=`(date = format(timestamp, format = "%F"))] timeframe_var <- "active_dates" } else if (timeframe == "week") { wt[, `:=`(week = format(timestamp, format = "%Y week %W"))] timeframe_var <- "active_weeks" } else if (timeframe == "month") { wt[, `:=`(month = format(timestamp, format = "%Y month %m"))] timeframe_var <- "active_months" } else if (timeframe == "year") { wt[, `:=`(year = format(timestamp, format = "%Y"))] timeframe_var <- "active_years" } else if (timeframe == "wave") { vars_wt <- names(wt) wave <- pmatch("wave", vars_wt) if (is.na(wave)) { stop("couldn't find the column 'wave' in the webtrack data", call. = FALSE) } else { timeframe_var <- "active_waves" } } summary <- wt[, list(temp = length(unique(get(timeframe)))), by = "panelist_id"] data.table::setnames(summary, "temp", timeframe_var) summary[] }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/summarize.R
#' Check if columns are present #' @description #' `vars_exist()` checks if columns are present in a webtrack data object. #' By default, checks whether the data has a `panelist_id`, a `ulr` and a #' `timestamp` column.#' #' @param wt webtrack data object. #' @param vars character vector of variables. #' Defaults to `c("panelist_id", "url", "timestamp")`. #' @return A data.table object. vars_exist <- function(wt, vars = c("panelist_id", "url", "timestamp")) { vars_wt <- names(wt) idx <- pmatch(vars, vars_wt) if (any(is.na(idx))) { not_found <- is.na(idx) err <- paste0("'", paste0(vars[not_found], collapse = "', '"), "'") stop(paste0("couldn't find the column(s) ", err, " in the webtrack data"), call. = FALSE) } invisible(NULL) } # Check if a data.table is valid webtrack data # @param wt webtrack data as data.table object # @param processed logical. If TRUE, also checks if "duration" and "domain" are present. Otherwise just checks if the standard columns exist # @param verbose should details be printed or not # @return logical if wt is valid webtrack data or not # is_valid_wt <- function(wt, processed = TRUE, verbose = TRUE){ # wt_vars_opt <- c("panelist_id", "url", "timestamp", "duration", "domain") # tick <- "\u2714" # cross <- "\u2716" # # if(!processed){ # wt_vars_opt <- wt_vars_opt[1:3] # } # # wt_vars_dat <- names(wt) # wt_vars_idx <- pmatch(wt_vars_opt,wt_vars_dat) # if(verbose){ # # TODO: add message here # } # if(any(is.na(wt_vars_idx))){ # return(FALSE) # } else{ # return(TRUE) # } # }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/utils.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start #' @importFrom data.table := #' @importFrom data.table .BY #' @importFrom data.table .EACHI #' @importFrom data.table .GRP #' @importFrom data.table .I #' @importFrom data.table .N #' @importFrom data.table .NGRP #' @importFrom data.table .SD #' @importFrom data.table data.table ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/webtrackR-package.R
#' An S3 class, based on [data.table], to store web tracking data #' @details #' A `wt_dt` table is a [data.table]. #' Therefore, it can be used by any function that would work on a [data.frame] or a [data.table]. #' Most of the operation such as variable creation, subsetting and joins are inherited from the [data.table] #' `[]` operator, following the convention `DT[i,j,by]` (see data table package for detail). #' @name wt_dt #' @seealso #' * [data.table] -- on which `wt_dt` is based NULL # Construction ------------------------------------------------------------ #' Convert a data.frame containing web tracking data to a `wt_dt` object #' @rdname wt_dt #' @param x data.frame containing a necessary set of columns, namely #' panelist's ID, visit URL and visit timestamp. #' @param varnames Named vector of column names, which contain the panelist's ID #' (`panelist_id`), the visit's URL (`url`) and the visit's timestamp (`timestamp`). #' @param timestamp_format string. Specifies the raw timestamp's formatting. #' Defaults to `"%Y-%m-%d %H:%M:%OS"`. #' @return a webtrack data object with at least columns `panelist_id`, `url` #' and `timestamp` #' @examples #' data("testdt_tracking") #' wt <- as.wt_dt(testdt_tracking) #' is.wt_dt(wt) #' @export as.wt_dt <- function(x, timestamp_format = "%Y-%m-%d %H:%M:%OS", varnames = c(panelist_id = "panelist_id", url = "url", timestamp = "timestamp")) { standard_vars <- c("panelist_id", "url", "timestamp") if (!inherits(x, "data.frame")) { stop("x must be a data.frame comparable object (tibble,data.table,..)") } if (!all(names(varnames) %in% standard_vars)) { stop("varnames must include mappings for 'panelist_id', 'url', and 'timestamp'") } if (!all(standard_vars %in% names(varnames))) { idx <- which(!standard_vars %in% names(varnames)) named_standard_vars <- standard_vars names(named_standard_vars) <- standard_vars varnames <- c(varnames, named_standard_vars[idx]) } if (!data.table::is.data.table(x)) { x <- data.table::as.data.table(x) } vars_exist(x, vars = varnames) x[, varnames[["timestamp"]] := as.POSIXct(get(varnames[["timestamp"]]), format = timestamp_format)] data.table::setnames(x, unname(varnames), names(varnames)) data.table::setorder(x, panelist_id, timestamp) class(x) <- c("wt_dt", class(x)) x } #' @rdname wt_dt #' @return logical. TRUE if x is a webtrack data object and FALSE otherwise #' @export is.wt_dt <- function(x) { data.table::is.data.table(x) & "wt_dt" %in% class(x) } # printing ------ #' @keywords internal print_wt_dt <- function(x, ...) { print_txt <- utils::capture.output(print(tibble::as_tibble(x), ...)) print_txt[1] <- sub("A tibble", "webtrack data", print_txt[1]) cat(print_txt, sep = "\n") invisible(x) } #' Print web tracking data #' @param x object of class wt_dt #' @param ... additional parameters for print #' @return No return value, called for side effects #' @export print.wt_dt <- function(x, ...) { print_wt_dt(x, ...) } #' Summary function for web tracking data #' @param object object of class wt_dt #' @param ... additional parameters for summary #' @return No return value, called for side effects #' @export summary.wt_dt <- function(object, ...) { tick <- "\u2714" cross <- "\u2716" symbols <- c(cross, tick) no_panelist <- length(unique(object[["panelist_id"]])) time_window <- range(object[["timestamp"]]) idx <- (!is.na(pmatch(c("duration", "domain", "type"), names(object)))) + 1 # printing cat("\n ==== Overview ====\n\n") cat("panelists: ", no_panelist, "\n") cat("time window: ", as.character(time_window[1]), " - ", as.character(time_window[2]), "\n") cat("\n") cat("[", symbols[idx[1]], "] duration\n", sep = "") cat("[", symbols[idx[2]], "] domain\n", sep = "") cat("[", symbols[idx[3]], "] type\n", sep = "") cat("\n") if (!is.null(attr(object, "dummy"))) { urldummys <- attr(object, "dummy") cat("urldummy variables:", paste(urldummys, collapse = ",")) } if (!is.null(attr(object, "panelist"))) { panelist <- attr(object, "panelist") cat("panelist variables:", paste(panelist, collapse = ",")) } cat("\n") cat("\n ====== DATA ======\n\n") NextMethod(object, ...) }
/scratch/gouwar.j/cran-all/cranData/webtrackR/R/wt_dt.R
webuselist <- list( auto = "1978 Automobile Data", auto2 = "1978 Automobile Data", autornd = "Subset of 1978 Automobile Data", bplong = "fictional blood pressure data", bpwide = "fictional blood pressure data", cancer = "Patient Survival in Drug Trial", census = "1980 Census data by state", citytemp = "City Temperature Data", citytemp4 = "City Temperature Data", educ99gdp = "Education and GDP", gnp96 = "U.S. GNP, 1967-2002", lifeexp = "Life expectancy, 1998", network1 = "fictional network diagram data", network1a = "fictional network diagram data", nlsw88 = "U.S. National Longitudinal Study of Young Women (NLSW, 1988 extract)", nlswide1 = "U.S. National Longitudinal Study of Young Women (NLSW, 1988 extract)", pop2000 = "U.S. Census, 2000, extract", sandstone = "Subsea elevation of Lamont sandstone in an area of Ohio", sp500 = "S&P 500", surface = "NOAA Sea Surface Temperature", tsline1 = "simulated time-series data", tsline2 = "fictional data on calories consumed", uslifeexp = "U.S. life expectancy, 1900-1999", uslifeexp2 = "U.S. life expectancy, 1900-1940", voter = "1992 presidential voter data", xtline1 = "fictional data on calories consumed" ) webuse <- function(data, version = 15, envir = parent.frame()) { d <- read_dta(paste0("https://www.stata-press.com/data/r",version,"/",data,".dta")) assign(data, d, envir = envir) invisible(d) }
/scratch/gouwar.j/cran-all/cranData/webuse/R/webuse.R
#' Demo multipart parser with httpuv #' #' Starts the httpuv web server and hosts a simple form including a file #' upload to demo the multipart parser. # #' @export #' @family demo #' @param port which port number to run the http server demo_httpuv <- function(port = 9359){ rook_handler <- function(env){ # See Rook spec content_type <- env[["CONTENT_TYPE"]] http_method <- env[["REQUEST_METHOD"]] body <- env[["rook.input"]]$read() path <- env[["PATH_INFO"]] # Show HTML page for GET requests. if(tolower(http_method) %in% c("post", "put")){ # Parse the multipart/form-data message("Received HTTP POST request.") postdata <- parse_http(body, content_type) # Print it to the R console (just for fun) utils::str(postdata) # process this form username <- rawToChar(as.raw(postdata$username$value)) email <- rawToChar(as.raw(postdata$email_address$value)) food <- rawToChar(as.raw(postdata$food$value)) picture <- file.path(getwd(), basename(postdata$picture$filename)) writeBin(postdata$picture$value, picture) # return summary to the client list( status = 200, body = paste0("User: ", username, "\nEmail: ", email, "\nPicture (copy): ", picture,"\nFood: ", food, "\n"), headers = c("Content-Type" = "text/plain") ) } else { message("Received HTTP GET request: ", path) testpage <- system.file("testpage.html", package="webutils"); stopifnot(file.exists(testpage)) list ( status = 200, body = paste(readLines(testpage), collapse="\n"), headers = c("Content-Type" = "text/html") ) } } # Start httpuv if(!length(port)) port <- httpuv::randomPort() server_id <- httpuv::startServer("0.0.0.0", port, list(call = rook_handler)) on.exit({ message("stopping server") httpuv::stopServer(server_id) }, add = TRUE) url <- paste0("http://localhost:", port, "/") message("Opening ", url) utils::browseURL(url) repeat { httpuv::service() } }
/scratch/gouwar.j/cran-all/cranData/webutils/R/demo_httpuv.R
#' Demo multipart parser with rhttpd #' #' Starts the Rhttpd web server and hosts a simple form including a file #' upload to demo the multipart parser. # #' @export #' @family demo demo_rhttpd <- function(){ rhttpd_handler <- function(reqpath, reqquery, reqbody, reqheaders){ # Extract HTTP content type and method from strange rhttpd format content_type <- grep("Content-Type:", strsplit(rawToChar(reqheaders), "\n")[[1]], ignore.case=TRUE, value=TRUE); content_type <- sub("Content-Type: ?", "", content_type, ignore.case=TRUE); http_method <- grep("Request-Method:", strsplit(rawToChar(reqheaders), "\n")[[1]], ignore.case=TRUE, value=TRUE); http_method <- sub("Request-Method: ?", "", http_method, ignore.case=TRUE); # Show HTML page for GET requests. if(tolower(http_method) %in% c("post", "put") && length(reqbody)){ # Parse the multipart/form-data message("Received HTTP POST request.") # Check for multipart() postdata <- parse_http(reqbody, content_type) # Print it to the R console (just for fun) utils::str(postdata) # process this form username <- rawToChar(as.raw(postdata$username$value)) email <- rawToChar(as.raw(postdata$email_address$value)) food <- rawToChar(as.raw(postdata$food$value)) picture <- file.path(getwd(), basename(postdata$picture$filename)) writeBin(as.raw(postdata$picture$value), picture) # return summary to the client list( "payload" = paste0("User: ", username, "\nEmail: ", email, "\nPicture (copy): ", picture,"\nFood: ", food, "\n"), "content-type" = "text/plain", "headers" = NULL, "status code" = 200 ) } else { message("Received HTTP GET request: ", reqpath) testpage <- system.file("testpage.html", package="webutils"); stopifnot(file.exists(testpage)) list( "payload" = readBin(testpage, raw(), n=file.info(testpage)$size), "content-type" = "text/html", "headers" = NULL, "status code" = 200 ) } } # Start rhttpd and get port port <- if(R.version[["svn rev"]] < 67550) { try(tools::startDynamicHelp(TRUE), silent=TRUE); utils::getFromNamespace("httpdPort", "tools"); } else { tools::startDynamicHelp(NA); } handlers_env <- utils::getFromNamespace(".httpd.handlers.env", "tools") assign("test", rhttpd_handler, handlers_env) url <- paste0("http://localhost:", port, "/custom/test") message("Opening ", url) utils::browseURL(url) }
/scratch/gouwar.j/cran-all/cranData/webutils/R/demo_rhttpd.R
get_boundary <- function(content_type){ # Check for multipart header if(!grepl("multipart/form-data;", content_type, fixed = TRUE)) stop("Content type is not multipart/form-data: ", content_type) if(!grepl("boundary=", content_type, fixed = TRUE)) stop("Multipart content-type header without boundary: ", content_type) # Extract bounary m <- regexpr('boundary=[^; ]{2,}', content_type, ignore.case = TRUE) boundary <- sub('boundary=','',regmatches(content_type, m)[[1]]) sub('^"(.*)"$', "\\1", boundary) }
/scratch/gouwar.j/cran-all/cranData/webutils/R/get_boundary.R
#' Parse http request #' #' Parse the body of a http request, based on the \code{Content-Type} request #' header. Currently supports the three most important content types: #' \code{application/x-www-form-urlencoded} (\code{\link{parse_query}}), #' \code{multipart/form-data} (\code{\link{parse_multipart}}) and #' \code{application/json} (\code{\link{fromJSON}}). #' #' @export #' @param body request body of the http request #' @param content_type content-type http request header as specified by the client #' @param ... additional arguments passed to parser function #' @importFrom jsonlite fromJSON #' @examples # Parse json encoded payload: #' parse_http('{"foo":123, "bar":true}', 'application/json') #' #' # Parse url-encoded payload #' parse_http("foo=1%2B1%3D2&bar=yin%26yang", "application/x-www-form-urlencoded") #' #' \dontrun{use demo app to parse multipart/form-data payload #' demo_rhttpd() #' } parse_http <- function(body, content_type, ...){ # Remove header name if present content_type <- sub("Content-Type: ?", "", content_type, ignore.case=TRUE); # Switch by content-type if(grepl("multipart/form-data;", content_type, fixed = TRUE)){ return(parse_multipart(body, get_boundary(content_type))) } else if(grepl("application/x-www-form-urlencoded", content_type, fixed=TRUE)){ return(parse_query(body)) } else if(grepl("(text|application)/json", content_type)){ if(is.raw(body)) body <- rawToChar(body) return(fromJSON(body, ...)) } else { stop("Unsupported Content-Type: ", content_type) } }
/scratch/gouwar.j/cran-all/cranData/webutils/R/parse_http.R
#' Parse a multipart/form-data request #' #' Parse a multipart/form-data request, which is usually generated from a HTML form #' submission. The parameters can include both text values as well as binary files. #' They can be distinguished from the presence of a \code{filename} attribute. #' #' A multipart/form-data request consists of a single body which contains one or more #' values plus meta-data, separated using a boundary string. This boundary string #' is chosen by the client (e.g. the browser) and specified in the \code{Content-Type} #' header of the HTTP request. There is no escaping; it is up to the client to choose #' a boundary string that does not appear in one of the values. #' #' The parser is written in pure R, but still pretty fast because it uses the regex #' engine. #' #' @export #' @param body body of the HTTP request. Must be raw or character vector. #' @param boundary boundary string as specified in the \code{Content-Type} request header. #' @examples \dontrun{example form #' demo_rhttpd() #' } parse_multipart <- function(body, boundary){ # Some HTTP daemons give the body as a string instead of raw. if(is.character(body)) body <- charToRaw(paste(body, collapse="")) if(is.character(boundary)) boundary <- charToRaw(boundary) # Heavy lifting in C stopifnot(is.raw(body), is.raw(boundary)) form_data <- split_by_boundary(body, boundary) # Output out <- lapply(form_data, function(val){ headers <- parse_header(val[[1]]) c(list( value = val[[2]] ), headers) }) names(out) <- sapply(out, `[[`, 'name'); out } parse_header <- function(buf){ headers <- strsplit(rawToChar(buf), "\r\n", fixed = TRUE)[[1]] out <- split_names(headers, ": ") if(length(out$content_disposition)){ pieces <- strsplit(out$content_disposition, "; ")[[1]] out$content_disposition <- pieces[1] out <- c(out, lapply(split_names(pieces[-1], "="), unquote)) } out } #' @useDynLib webutils R_split_boundary split_by_boundary <- function(body, boundary){ .Call(R_split_boundary, body, boundary) } #' @useDynLib webutils R_split_string split_by_string <- function(string, split = ":"){ .Call(R_split_string, string, split) } #' @useDynLib webutils R_unquote unquote <- function(string){ .Call(R_unquote, string) } split_names <- function(x, split){ matches <- lapply(x, split_by_string, split) names <- chartr("-", "_", tolower(sapply(matches, `[[`, 1))) values <- lapply(matches, `[[`, 2) structure(values, names = names); }
/scratch/gouwar.j/cran-all/cranData/webutils/R/parse_multipart.R
#' Parse query string #' #' Parse http parameters from a query string. This includes unescaping #' of url-encoded values. #' #' For http GET requests, the query string is specified #' in the URL after the question mark. For http POST or PUT requests, the query #' string can be used in the request body when the \code{Content-Type} header #' is set to \code{application/x-www-form-urlencoded}. #' #' @export #' @param query a url-encoded query string #' @examples q <- "foo=1%2B1%3D2&bar=yin%26yang" #' parse_query(q) parse_query <- function(query){ if(is.raw(query)) query <- rawToChar(query); stopifnot(is.character(query)); #httpuv includes the question mark in query string query <- sub("^[?]", "", query) query <- chartr('+',' ', query) #split by & character argstr <- strsplit(query, "&", fixed = TRUE)[[1]] args <- lapply(argstr, function(x){ curl::curl_unescape(strsplit(x, "=", fixed = TRUE)[[1]]) }) values <- lapply(args, `[`, 2) names(values) <- vapply(args, `[`, character(1), 1) return(values) }
/scratch/gouwar.j/cran-all/cranData/webutils/R/parse_query.R
# Override default for call. argument stop <- function(..., call. = FALSE){ base::stop(..., call. = FALSE) } # Strip trailing whitespace trail <- function(str){ str <- sub("\\s+$", "", str, perl = TRUE); sub("^\\s+", "", str, perl = TRUE); } rawToChar <- function(x){ out <- base::rawToChar(x) Encoding(out) <- 'UTF-8' out }
/scratch/gouwar.j/cran-all/cranData/webutils/R/util.R
contr.wec <- function(x, omitted) { frequencies <- table(x) n.cat <- length(table(x)) omitted <- which(levels(x) == omitted) new.contrasts <- contr.treatment(n.cat, base=omitted) new.contrasts[omitted,] <- -1 * frequencies[-omitted] / frequencies[omitted] colnames(new.contrasts) <- names(frequencies[-omitted]) return(new.contrasts) }
/scratch/gouwar.j/cran-all/cranData/wec/R/contr.wec.R
wec.interact <- function (x1, x2, output.contrasts = FALSE) { if (class(x1) != "factor") { stop("x1 needs to be a factor variable") } if (class(x2) == "factor") { mm <- model.matrix(~x1 * x2) mm <- mm[, -1] mm.full <- mm mm <- unique(mm) n.int <- (length(levels(x1)) - 1) * (length(levels(x2)) - 1) n.main <- (length(levels(x1)) - 1) + (length(levels(x2)) - 1) mm.int <- matrix(mm[, (dim(mm)[2] - n.int + 1):dim(mm)[2]], ncol=n.int) colnames(mm.int) <- colnames(mm)[-(1:n.main)] rownames(mm.int) <- rownames(mm) mm.main <- mm[, 1:n.main] ref.x1 <- paste(names(attr(table(x1, x2), "dimnames"))[1], names(table(x1)), sep = "") ref.x2 <- paste(names(attr(table(x1, x2), "dimnames"))[2], names(table(x2)), sep = "") reftable <- matrix(data = NA, nrow = length(table(x1)), ncol = length(table(x2))) for (i in 1:dim(reftable)[1]) { for (j in 1:dim(reftable)[2]) { reftable[i, j] <- paste(ref.x1[i], ref.x2[j], sep = ":") } } refcat.x1 <- setdiff(rownames(contrasts(x1)), colnames(contrasts(x1))) refcat.x2 <- setdiff(rownames(contrasts(x2)), colnames(contrasts(x2))) refcat.n <- table(x1, x2)[refcat.x1, refcat.x2] cond1 <- apply(mm.main < 0, 1, sum) == n.main values <- NA for (i in 1:ncol(mm.int)) { values[i] <- table(x1, x2)[which(reftable == colnames(mm.int)[i], arr.ind = TRUE)]/refcat.n } mm.int[cond1, ] <- rep(values, each = sum(cond1)) cond2 <- which(mm.int < 0, arr.ind = TRUE) for (i in 1:nrow(cond2)) { num <- table(x1, x2)[which(reftable == colnames(mm.int)[cond2[i, 2]])] denom <- table(x1, x2)[x1[as.numeric(rownames(cond2)[i])], x2[as.numeric(rownames(cond2)[i])]] mm.int[cond2[i, 1], cond2[i, 2]] <- -1 * num/denom } mm[, -1:-n.main] <- mm.int if (output.contrasts) { warning("When interacting to weighted effect coded variables, coding matrix cannot be used to set contrasts.") ind <- as.numeric(row.names(mm.int)) rownames(mm.int) <- paste(x1[ind], x2[ind], sep = ":") return(mm.int) } mm.full <- mm.full[, 1:n.main] mm.full <- as.data.frame(mm.full) mm <- as.data.frame(mm) output.data <- left_join(mm.full, mm, by = names(mm.full)) output.data <- output.data[, -1:-n.main] output.data <- as.matrix(output.data) return(output.data) } if (class(x2) != "factor") { ref <- which(apply(contrasts(x1), 1, sum) != 1) weights <- tapply(x2, x1, function(x) { sum((x - mean(x))^2) }) weights <- -1 * weights/weights[ref] effect.matrix <- contr.sum(length(levels(x1))) effect.matrix[-ref, ] <- effect.matrix[1:length(levels(x1)) - 1, ] effect.matrix[ref, ] <- weights[-ref] if (output.contrasts) { return(effect.matrix) } colnames(effect.matrix) <- names(weights)[-ref] rownames(effect.matrix) <- names(weights) interact <- x1 contrasts(interact) <- effect.matrix output <- model.matrix(~interact)[, -1] * x2 output <- apply(output, 2, function(x) x - ave(x, x1)) return(output) } }
/scratch/gouwar.j/cran-all/cranData/wec/R/wec.interact.R
#' GeoCodes text locations using the GeoNames API #' @description Uses the ``location_word`` and ``Country`` columns of the data frame to make queries #' to the geonames API and geocode the locations in the dataset. #' #' Note: #' 1) The Geonames API (for free accounts) limits you to 1000 queries an hour #' 2) You need a geonames username to make queries. You can learn more about that [here](https://www.geonames.org/manual.html) #' #' @param . a data frame which has been locationized (see ``weed::split_locations``) #' @param n_results number of lat/longs to get #' @param unwrap if true, returns lat1, lat2, lng1, lng2 etc. as different columns, otherwise one lat column and 1 lng column #' @param geonames_username Username for geonames API. More about getting one is in the note above. #' #' @return the same data frame with a lat column/columns and lng column/columns #' @export #' #' #' @examples #' df <- tibble::tribble( #' ~value, ~location_word, ~Country, #' "mumbai region, district of seattle, sichuan province", "mumbai","India", #' "mumbai region, district of seattle, sichuan province", "seattle", "USA" #' ) #' geocode(df, n_results = 1, unwrap = TRUE, geonames_username = "rammkripa") #' #' #' @importFrom magrittr %>% geocode <- function(., n_results = 1, unwrap = FALSE, geonames_username) { options(geonamesUsername = geonames_username) location_word <- Country <- location_data <- lat <- lng <- NULL df <- . new_df <- df %>% dplyr::mutate(location_data = purrr::pmap(list(location_word, Country, n_results), get_lat_long)) %>% tidyr::unnest_wider(col = location_data) if (unwrap) { new_df <- new_df %>% tidyr::unnest_wider(col = lat, names_sep = '') %>% tidyr::unnest_wider(col = lng, names_sep = '') } return(new_df) } cache_list <- list() get_lat_long <- function(location_name,country_name, n_result){ if (location_name %in% names(cache_list)){ return(cache_list[[location_name]]) } country_code <- countrycode::countrycode(sourcevar = country_name, origin = "country.name", destination = "iso2c") return_list <- geonames::GNsearch(q = location_name, country = country_code, type = "json" ) return_val <- tryCatch( expr = { toponymName <- lat <- lng <- NULL return_df <- return_list %>% dplyr::select(toponymName,lat,lng) %>% utils::head(n = n_result) %>% dplyr::mutate(lat = as.numeric(lat),lng = as.numeric(lng)) list("lat" = return_df$lat,"lng" = return_df$lng) }, error = function(e) { print(e) list("lat" = NA, "lng" = NA) } ) cache_list[[location_name]] <- return_val return(return_val) }
/scratch/gouwar.j/cran-all/cranData/weed/R/geocode.R
#' Geocode in batches #' #' #' @param . data frame #' @param batch_size size of each batch to geocode #' @param wait_time in seconds between batches #' Note: #' default batch_size and wait_time were set to accomplish the geocoding task optimally within the constraints of geonames free access #' @param n_results same as geocode #' @param unwrap as in geocode #' @param geonames_username as in geocode #' #' @return df geocoded #' @export #' #' @examples #' df <- tibble::tribble( #' ~value, ~location_word, ~Country, #' "mumbai region, district of seattle, sichuan province", "mumbai","India", #' "mumbai region, district of seattle, sichuan province", "seattle", "USA", #' "mumbai region, district of seattle, sichuan province", "sichuan", "China, People's Republic" #' ) #' #' geocode_batches(df, batch_size = 2, wait_time = 0.4, geonames_username = "rammkripa") #' #' @importFrom magrittr %>% geocode_batches <- function(., batch_size = 990, wait_time = 4800, n_results = 1, unwrap = FALSE, geonames_username) { df <- . num_batches <- ((nrow(df) - 1) %/% batch_size) + 1 listy <- list() for (batch_num in 0:(num_batches-1)) { print("batch number") print(batch_num + 1) start.idx <- batch_num * batch_size end.idx <- min(c((batch_num + 1) * batch_size, nrow(df)) ) - 1 start.idx <- start.idx + 1 end.idx <- end.idx + 1 df_slice <- dplyr::slice(df, start.idx:end.idx) coded_slice <- df_slice %>% geocode(n_results, unwrap, geonames_username) listy[[batch_num + 1]] = coded_slice print("waiting for ") print(wait_time) print("seconds") Sys.sleep(wait_time) } return(dplyr::bind_rows(listy)) }
/scratch/gouwar.j/cran-all/cranData/weed/R/geocode_batches.R
#' Locations In the Box #' @description Creates a new column (in_box) that tells whether the lat/long is in a certain box or not. #' @param . Data Frame that has been locationized. see ``weed::split_locations`` #' @param lat_column Name of column containing Latitude data #' @param lng_column Name of column containing Longitude data #' @param top_left_lat Latitude at top left corner of box #' @param top_left_lng Longitude at top left corner of box #' @param bottom_right_lat Latitude at bottom right corner of box #' @param bottom_right_lng Longitude at bottom right corner of box #' #' @return A dataframe that contains the latlong box data #' @export #' #' @examples #' d <- tibble::tribble( #' ~value, ~location_word, ~Country, ~lat, ~lng, #' "city of new york", "new york", "USA", 40.71427, -74.00597, #' "kerala, chennai municipality, and san francisco", "kerala", "India", 10.41667, 76.5, #' "kerala, chennai municipality, and san francisco", "chennai", "India", 13.08784, 80.27847) #' located_in_box(d, lat_column = "lat", #' lng_column = "lng", #' top_left_lat = 45, #' bottom_right_lat = 12, #' top_left_lng = -80, #' bottom_right_lng = 90) #' @importFrom magrittr %>% located_in_box <- function(., lat_column = "lat", lng_column = "lng", top_left_lat, top_left_lng, bottom_right_lat, bottom_right_lng) { lng <- NA lat <- NA df <- . new_df <- df %>% dplyr::rename("lat" = lat_column, "lng" = lng_column) inbox_df <- new_df %>% dplyr::mutate(in_box = (lat >= bottom_right_lat) & (lat <= top_left_lat) & (lng >= top_left_lng) & (lng <= bottom_right_lng)) return (inbox_df) }
/scratch/gouwar.j/cran-all/cranData/weed/R/located_in_box.R
#' Locations In the Shapefile #' @description Creates a new column (in_shape) that tells whether the lat/long is in a certain shapefile. #' @param . Data Frame that has been locationized. see ``weed::split_locations`` #' @param lat_column Name of column containing Latitude data #' @param lng_column Name of column containing Longitude data #' @param shapefile_name FileName/Path to shapefile (either shapefile or shapefile_name must be provided) #' @param shapefile The shapefile itself (either shapefile or shapefile_name must be provided) #' #' @return Data Frame with the shapefile data as well as the previous data #' @export #' #' @examples #' \dontrun{ #' d <- tibble::tribble( #' ~value, ~location_word, ~Country, ~lat, ~lng, #' "city of new york", "new york", "USA", 40.71427, -74.00597, #' "kerala, chennai municipality, and san francisco", "kerala", "India", 10.41667, 76.5, #' "kerala, chennai municipality, and san francisco", "chennai", "India", 13.08784, 80.2847) #' located_in_shapefile(d, #' lat_column = "lat", #' lng_column = "lng", #' shapefile_name = "~/dummy_name") #' } #' @importFrom magrittr %>% located_in_shapefile <- function(., lat_column = "lat", lng_column = "lng", shapefile = NA, shapefile_name = NA) { lng <- NA lat <- NA s_file <- NA if (is.na(shapefile)) { if (is.na(shapefile_name)) { print("ERROR : Must provide either shapefile or shapefile_name") return(NA) } else { s_name <- shapefile_name s_file <- sf::st_read(s_name) } } else { s_file <- shapefile } df <- . new_df <- df %>% dplyr::rename_("lat" = lat_column, "lng" = lng_column) lat_long_key_df <- new_df %>% dplyr::select(lat, lng) %>% sf::st_as_sf(coords = c("lng", "lat"), crs = sf::st_crs(s_file)) inshape_key_df <- sf::st_contains(y = lat_long_key_df, x = s_file, sparse = FALSE) inshape_key_vec <- inshape_key_df[1, ] new_df %>% dplyr::mutate(in_shape = inshape_key_vec) %>% return() }
/scratch/gouwar.j/cran-all/cranData/weed/R/located_in_shapefile.R
#' Nest Location Data into a column of Tibbles #' #' @param . Locationized data frame (see ``weed::split_locations``) #' @param key_column Column name for Column that uniquely IDs each observation #' @param columns_to_nest Column names for Columns to nest inside the mini-dataframes #' @param keep_nested_cols Boolean to Keep the nested columns externally or not. #' #' @return Data Frame with A column of data frames #' @export #' #' @examples #' d <- tibble::tribble( #' ~value, ~location_word, ~Country, ~lat, ~lng, #' "city of new york","new york","USA", c(40.71427, 40.6501), c(-74.00597, -73.94958), #' "kerala", "kerala", "India",c(10.41667, 8.4855), c(76.5, 76.94924), #' "chennai municipality","chennai","India", c(13.08784, 12.98833),c(80.27847, 80.16578), #' "san francisco", "san francisco","USA", c(37.77493, 37.33939), c(-122.41942, -121.89496)) #' nest_locations(d, key_column = "value") #' #' @importFrom magrittr %>% nest_locations <- function(., key_column = "Dis No", columns_to_nest = c("location_word","lat","lng"), keep_nested_cols = FALSE) { df <- . naming_func <- function(argument) { return(key_column) } bud <- df %>% dplyr::select(c(columns_to_nest,key_column)) %>% dplyr::group_nest(get(key_column)) %>% dplyr::rename_with(.fn = naming_func, .cols = "get(key_column)") joint <- df %>% dplyr::left_join(y = bud, by = key_column) %>% dplyr::rename("location_data" = "data") if (keep_nested_cols) { return(joint) } else { joint %>% dplyr::select(!columns_to_nest) %>% return() } }
/scratch/gouwar.j/cran-all/cranData/weed/R/nest_locations.R
#' Percent of Disasters Successfully Geocoded #' @description Tells us how successful the geocoding is. #' @description How many of the disasters in this data frame have non NA coordinates? #' @param . Data Frame that has been locationized. see ``weed::split_locations`` #' @param how takes in a function, "any", or "all" to determine how to count the disaster as being geocoded #' if any, at least one location must be coded, if all, all locations must have lat/lng #' if a function, it must take in a logical vector and return a single logical #' @param lat_column Name of column containing Latitude data #' @param lng_column Name of column containing Longitude data #' @param plot_result Determines output type (Plot or Summarized Data Frame) #' #' @return The percent and number of Locations that have been geocoded (see ``plot_result`` for type of output) #' @export #' #' @examples #' d <- tibble::tribble( #' ~`Dis No`, ~value, ~location_word, ~Country, ~lat, ~lng, #' 1, "city of new york", "new york", "USA", 40.71427, -74.00597, #' 2, "kerala, chennai municipality, and san francisco", "kerala", "India", 10.41667, 76.5, #' 2, "kerala, chennai municipality, and san francisco", "chennai", "India", 13.08784, 80.27847) #' percent_located_disasters(d, #' how = "any", #' lat_column = "lat", #' lng_column = "lng", #' plot_result = FALSE) #' #' @importFrom magrittr %>% percent_located_disasters <- function(., how = "any", lat_column = "lat", lng_column = "lng", plot_result = TRUE) { df <- . # Global Variables lat <- lng <- coords_existent <- count <- percent <- uptown_func <- `Dis No` <- NULL if (how == "any") { uptown_func <- any } else if (how == "all") { uptown_func <- all } else { uptown_func <- how } new_df <- df %>% dplyr::rename("lat" = lat_column, "lng" = lng_column) perc_df <- new_df %>% dplyr::mutate(coords_existent = !(is.na(lat) & is.na(lng))) %>% dplyr::group_by(`Dis No`) %>% dplyr::summarize(coords_existent = uptown_func(coords_existent)) %>% dplyr::group_by(coords_existent) %>% dplyr::summarize(count = dplyr::n()) %>% dplyr::mutate(percent = 100*count/sum(count)) %>% dplyr::mutate(coords_existent = forcats::as_factor(coords_existent)) %>% dplyr::mutate(coords_existent = forcats::fct_recode(coords_existent, "Geocode Failed" = "FALSE", "Geocode Success" = "TRUE")) if (plot_result){ perc_df %>% ggplot2::ggplot(mapping = ggplot2::aes(x = coords_existent, y = percent, fill = coords_existent))+ ggplot2::geom_col() + ggplot2::ylim(0,100) + ggplot2::xlab("Geocoding") + ggplot2::ylab("Percent of Disasters") + ggplot2::ggtitle("Percent of Disasters Geocoded") + ggplot2::coord_flip() + ggplot2::theme(legend.title = ggplot2::element_blank()) + ggplot2::scale_color_manual(aesthetics = 'fill', values = c('Geocode Failed' = 'red', 'Geocode Success' = 'blue')) } else { return(perc_df) } }
/scratch/gouwar.j/cran-all/cranData/weed/R/percent_located_disasters.R
#' Percent of Locations Successfully Geocoded #' @description Tells us how successful the geocoding is. #' @description How many of the locations in this data frame have non NA coordinates? #' @param . Data Frame that has been locationized. see ``weed::split_locations`` #' @param lat_column Name of column containing Latitude data #' @param lng_column Name of column containing Longitude data #' @param plot_result Determines output type (Plot or Summarized Data Frame) #' #' @return The percent and number of Locations that have been geocoded (see ``plot_result`` for type of output) #' @export #' #' @examples #' d <- tibble::tribble( #' ~value, ~location_word, ~Country, ~lat, ~lng, #' "city of new york", "new york", "USA", 40.71427, -74.00597, #' "kerala, chennai municipality, and san francisco", "kerala", "India", 10.41667, 76.5, #' "kerala, chennai municipality, and san francisco", "chennai", "India", 13.08784, 80.27847) #' percent_located_locations(d, #' lat_column = "lat", #' lng_column = "lng", #' plot_result = FALSE) #' #' @importFrom magrittr %>% percent_located_locations <- function(., lat_column = "lat", lng_column = "lng", plot_result = TRUE) { df <- . # Global Variables lat <- lng <- coords_nonexistent <- count <- percent <- NULL new_df <- df %>% dplyr::rename("lat" = lat_column, "lng" = lng_column) perc_df <- new_df %>% dplyr::mutate(coords_nonexistent = is.na(lat) & is.na(lng)) %>% dplyr::group_by(coords_nonexistent) %>% dplyr::summarize(count = dplyr::n()) %>% dplyr::mutate(percent = 100*count/sum(count)) %>% dplyr::mutate(coords_nonexistent = forcats::as_factor(coords_nonexistent)) %>% dplyr::mutate(coords_nonexistent = forcats::fct_recode(coords_nonexistent, "Geocode Failed" = "TRUE", "Geocode Success" = "FALSE")) if (plot_result){ perc_df %>% ggplot2::ggplot(mapping = ggplot2::aes(x = coords_nonexistent, y = percent, fill = coords_nonexistent))+ ggplot2::geom_col() + ggplot2::ylim(0,100) + ggplot2::xlab("Geocoding") + ggplot2::ylab("Percent of Locations") + ggplot2::ggtitle("Percent of Locations Geocoded") + ggplot2::coord_flip()+ ggplot2::theme(legend.title = ggplot2::element_blank()) + ggplot2::scale_color_manual(aesthetics = 'fill', values = c('Geocode Failed' = 'red', 'Geocode Success' = 'blue')) } else { return(perc_df) } }
/scratch/gouwar.j/cran-all/cranData/weed/R/percent_located_locations.R
#' Reads Excel Files obtained from EM-DAT Database #' @description Reads Excel files downloaded from the EMDAT Database linked [here](https://public.emdat.be/) #' @param path_to_file A String, the Path to the file downloaded. #' @param file_data A Boolean, Do you want information about the file and how it was created? #' #' @return Returns a list containing one or two tibbles, one for the Disaster Data, and one for File Metadata. #' @export #' #' @examples #' \dontrun{ #' read_emdat(path_to_file = "~/dummy", file_data = TRUE) #' } #' @importFrom magrittr %>% read_emdat <- function(path_to_file, file_data = TRUE){ disaster_data <- readxl::read_excel(path = path_to_file, skip = 6, col_names = TRUE) meta_data <- readxl::read_excel(path = path_to_file, n_max = 6, col_names = FALSE) %>% dplyr::rename("Q" = "...1", "A" = "...2") return_list <- list() if(file_data) { return_list[["file_data"]] <- meta_data } return_list[["disaster_data"]] <- disaster_data return(return_list) }
/scratch/gouwar.j/cran-all/cranData/weed/R/read_emdat.R
#' Splits string of manually entered locations into one row for each location #' @description Changes the unit of analysis from a disaster, to a disaster-location. This is useful as preprocessing before geocoding each disaster-location pair. #' @description Can be used in piped operations, making it tidy! #' @param . data frame of disaster data #' @param column_name name of the column containing the locations #' @param dummy_words a vector of words that we don't want in our final output. #' @param joiner_regex a regex that tells us how to split the locations #' #' @return same data frame with the location_word column added as well as a column called uncertain_location_specificity where the same location could be referred to in varying levels of specificity #' @export #' #' @examples #' locs <- c("city of new york", "kerala, chennai municipality, and san francisco", #' "mumbai region, district of seattle, sichuan province") #' d <- tibble::as_tibble(locs) #' split_locations(d, column_name = "value") #' #' @importFrom magrittr %>% split_locations <- function(., column_name = "locations", dummy_words = c("cities","states","provinces","districts","municipalities","regions", "villages", "city","state","province","district","municipality","region", "township", "village", "near", "department"), joiner_regex = ",|\\(|\\)|;|\\+|( and )|( of )" ) { location_string <- location_word <- NULL df <- . dummy_words_regex <- stringr::str_c("(",stringr::str_c(dummy_words,collapse=")|("),")") new_df <- df %>% #dplyr::mutate(uncertain_location_specificity = stringr::str_detect(string = location_string, "\\(")) %>% tidytext::unnest_tokens(output = "location_word", input = column_name, token = stringr::str_split, pattern = joiner_regex) %>% dplyr::mutate(location_word = stringr::str_remove( string = location_word, pattern = dummy_words_regex)) %>% dplyr::mutate(location_word = stringr::str_trim(location_word)) %>% dplyr::filter(!stringr::str_detect(location_word, "^[0-9 ]+$")) %>% dplyr::filter(!stringr::str_detect(location_word, "^ +$")) %>% dplyr::filter(location_word!="") vec <- new_df[[column_name]] new_df <- new_df %>% dplyr::mutate(uncertain_location_specificity = stringr::str_detect(string = vec, "\\(")) return(new_df) }
/scratch/gouwar.j/cran-all/cranData/weed/R/split_locations.R
#' Get ESPN women's college basketball game data (play-by-play, team and player box) #' @author Saiem Gilani #' @param game_id Game ID #' @return A named list of dataframes: Plays, Team, Player #' #' **Plays** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |id |character | #' |sequence_number |character | #' |text |character | #' |away_score |integer | #' |home_score |integer | #' |scoring_play |logical | #' |score_value |integer | #' |wallclock |character | #' |shooting_play |logical | #' |type_id |integer | #' |type_text |character | #' |period_number |integer | #' |period_display_value |character | #' |clock_display_value |character | #' |team_id |integer | #' |coordinate_x_raw |numeric | #' |coordinate_y_raw |numeric | #' |coordinate_x |numeric | #' |coordinate_y |numeric | #' |play_id |character | #' |athlete_id_1 |integer | #' |athlete_id_2 |integer | #' |home_team_id |integer | #' |home_team_mascot |character | #' |home_team_name |character | #' |home_team_abbrev |character | #' |home_team_logo |character | #' |home_team_logo_dark |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_team_alternate_color |character | #' |home_team_score |integer | #' |home_team_winner |logical | #' |home_team_record |character | #' |away_team_id |integer | #' |away_team_mascot |character | #' |away_team_name |character | #' |away_team_abbrev |character | #' |away_team_logo |character | #' |away_team_logo_dark |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_team_alternate_color |character | #' |away_team_score |integer | #' |away_team_winner |logical | #' |away_team_record |character | #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' #' **Team** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |team_id |integer | #' |team_uid |character | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_logo |character | #' |team_home_away |character | #' |team_score |integer | #' |team_winner |logical | #' |assists |integer | #' |blocks |integer | #' |defensive_rebounds |integer | #' |field_goal_pct |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |flagrant_fouls |integer | #' |fouls |integer | #' |free_throw_pct |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |largest_lead |character | #' |offensive_rebounds |integer | #' |steals |integer | #' |team_turnovers |integer | #' |technical_fouls |integer | #' |three_point_field_goal_pct |numeric | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |total_rebounds |integer | #' |total_technical_fouls |integer | #' |total_turnovers |integer | #' |turnovers |integer | #' |opponent_team_id |integer | #' |opponent_team_uid |character | #' |opponent_team_slug |character | #' |opponent_team_location |character | #' |opponent_team_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_display_name |character | #' |opponent_team_short_display_name |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_logo |character | #' |opponent_team_score |integer | #' #' **Player** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |athlete_id |integer | #' |athlete_display_name |character | #' |team_id |integer | #' |team_name |character | #' |team_location |character | #' |team_short_display_name |character | #' |minutes |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |offensive_rebounds |integer | #' |defensive_rebounds |integer | #' |rebounds |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls |integer | #' |points |integer | #' |starter |logical | #' |ejected |logical | #' |did_not_play |logical | #' |active |logical | #' |athlete_jersey |character | #' |athlete_short_name |character | #' |athlete_headshot_href |character | #' |athlete_position_name |character | #' |athlete_position_abbreviation |character | #' |team_display_name |character | #' |team_uid |character | #' |team_slug |character | #' |team_logo |character | #' |team_abbreviation |character | #' |team_color |character | #' |team_alternate_color |character | #' |home_away |character | #' |team_winner |logical | #' |team_score |integer | #' |opponent_team_id |integer | #' |opponent_team_name |character | #' |opponent_team_location |character | #' |opponent_team_display_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_logo |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WBB Game #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_game_all(game_id = 401276115)) #' } espn_wbb_game_all <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") #---- Play-by-Play ------ tryCatch( expr = { plays_df <- helper_espn_wbb_pbp(resp) if (is.null(plays_df)) { message(glue::glue("{Sys.time()}: No play-by-play data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) #---- Team Box ------ tryCatch( expr = { team_box_score <- helper_espn_wbb_team_box(resp) if (is.null(team_box_score)) { message(glue::glue("{Sys.time()}: No team box score data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no team box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) #---- Player Box ------ tryCatch( expr = { player_box_score <- helper_espn_wbb_player_box(resp) if (is.null(player_box_score)) { message(glue::glue("{Sys.time()}: No player box score data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no player box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) pbp <- c(list(plays_df), list(team_box_score), list(player_box_score)) names(pbp) <- c("Plays", "Team", "Player") return(pbp) } #' Get ESPN women's college basketball play by play data #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a play-by-play data frame #' #' **Plays** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |id |character | #' |sequence_number |character | #' |text |character | #' |away_score |integer | #' |home_score |integer | #' |scoring_play |logical | #' |score_value |integer | #' |wallclock |character | #' |shooting_play |logical | #' |type_id |integer | #' |type_text |character | #' |period_number |integer | #' |period_display_value |character | #' |clock_display_value |character | #' |team_id |integer | #' |coordinate_x_raw |numeric | #' |coordinate_y_raw |numeric | #' |coordinate_x |numeric | #' |coordinate_y |numeric | #' |play_id |character | #' |athlete_id_1 |integer | #' |athlete_id_2 |integer | #' |home_team_id |integer | #' |home_team_mascot |character | #' |home_team_name |character | #' |home_team_abbrev |character | #' |home_team_logo |character | #' |home_team_logo_dark |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_team_alternate_color |character | #' |home_team_score |integer | #' |home_team_winner |logical | #' |home_team_record |character | #' |away_team_id |integer | #' |away_team_mascot |character | #' |away_team_name |character | #' |away_team_abbrev |character | #' |away_team_logo |character | #' |away_team_logo_dark |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_team_alternate_color |character | #' |away_team_score |integer | #' |away_team_winner |logical | #' |away_team_record |character | #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WBB PBP #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_pbp(game_id = 401498717)) #' } espn_wbb_pbp <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) tryCatch( expr = { resp <- res %>% httr::content(as = "text", encoding = "UTF-8") plays_df <- helper_espn_wbb_pbp(resp) if (is.null(plays_df)) { return(message(glue::glue("{Sys.time()}: No play-by-play data for {game_id} available!"))) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) return(plays_df) } #' Get ESPN women's college basketball team box data #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a team boxscore data frame #' #' **Team** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |team_id |integer | #' |team_uid |character | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_logo |character | #' |team_home_away |character | #' |team_score |integer | #' |team_winner |logical | #' |assists |integer | #' |blocks |integer | #' |defensive_rebounds |integer | #' |field_goal_pct |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |flagrant_fouls |integer | #' |fouls |integer | #' |free_throw_pct |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |largest_lead |character | #' |offensive_rebounds |integer | #' |steals |integer | #' |team_turnovers |integer | #' |technical_fouls |integer | #' |three_point_field_goal_pct |numeric | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |total_rebounds |integer | #' |total_technical_fouls |integer | #' |total_turnovers |integer | #' |turnovers |integer | #' |opponent_team_id |integer | #' |opponent_team_uid |character | #' |opponent_team_slug |character | #' |opponent_team_location |character | #' |opponent_team_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_display_name |character | #' |opponent_team_short_display_name |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_logo |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WBB Team Box #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_team_box(game_id = 401276115)) #' } espn_wbb_team_box <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) tryCatch( expr = { resp <- res %>% httr::content(as = "text", encoding = "UTF-8") team_box_score <- helper_espn_wbb_team_box(resp) if (is.null(team_box_score)) { return(message(glue::glue("{Sys.time()}: No team box score data for {game_id} available!"))) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no team box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) return(team_box_score) } #' Get ESPN women's college basketball player box #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a player boxscore data frame #' #' **Player** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |athlete_id |integer | #' |athlete_display_name |character | #' |team_id |integer | #' |team_name |character | #' |team_location |character | #' |team_short_display_name |character | #' |minutes |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |offensive_rebounds |integer | #' |defensive_rebounds |integer | #' |rebounds |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls |integer | #' |points |integer | #' |starter |logical | #' |ejected |logical | #' |did_not_play |logical | #' |active |logical | #' |athlete_jersey |character | #' |athlete_short_name |character | #' |athlete_headshot_href |character | #' |athlete_position_name |character | #' |athlete_position_abbreviation |character | #' |team_display_name |character | #' |team_uid |character | #' |team_slug |character | #' |team_logo |character | #' |team_abbreviation |character | #' |team_color |character | #' |team_alternate_color |character | #' |home_away |character | #' |team_winner |logical | #' |team_score |integer | #' |opponent_team_id |integer | #' |opponent_team_name |character | #' |opponent_team_location |character | #' |opponent_team_display_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_logo |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WBB Player Box #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_player_box(game_id = 401276115)) #' } espn_wbb_player_box <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) tryCatch( expr = { resp <- res %>% httr::content(as = "text", encoding = "UTF-8") player_box_score <- helper_espn_wbb_player_box(resp) if (is.null(player_box_score)) { return(message(glue::glue("{Sys.time()}: No player box score data for {game_id} available!"))) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no player box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) return(player_box_score) } #' **Get ESPN women's college basketball game rosters** #' @author Saiem Gilani #' @param game_id Game ID #' @return A game rosters data frame #' #' |col_name |types | #' |:------------------------|:---------| #' |athlete_id |integer | #' |athlete_uid |character | #' |athlete_guid |character | #' |athlete_type |character | #' |sdr |integer | #' |first_name |character | #' |last_name |character | #' |full_name |character | #' |athlete_display_name |character | #' |short_name |character | #' |height |integer | #' |display_height |character | #' |birth_place_city |character | #' |birth_place_state |character | #' |birth_place_country |character | #' |slug |character | #' |headshot_href |character | #' |headshot_alt |character | #' |jersey |character | #' |position_id |integer | #' |position_name |character | #' |position_display_name |character | #' |position_abbreviation |character | #' |position_leaf |logical | #' |linked |logical | #' |experience_years |integer | #' |experience_display_value |character | #' |experience_abbreviation |character | #' |active |logical | #' |status_id |integer | #' |status_name |character | #' |status_type |character | #' |status_abbreviation |character | #' |starter |logical | #' |valid |logical | #' |did_not_play |logical | #' |display_name |character | #' |ejected |logical | #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_nickname |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |is_active |logical | #' |is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' |game_id |integer | #' |order |integer | #' |home_away |character | #' |winner |logical | #' |roster_href |character | #' |hand_type |character | #' |hand_abbreviation |character | #' |hand_display_value |character | #' |age |integer | #' |date_of_birth |character | #' |weight |integer | #' |display_weight |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WBB Game Roster #' @family ESPN WBB Functions #' #' @examples #' \donttest{ #' try(espn_wbb_game_rosters(game_id = 401276115)) #' } espn_wbb_game_rosters <- function(game_id) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) tryCatch( expr = { play_base_url <- paste0( "https://sports.core.api.espn.com/v2/sports/basketball/leagues/womens-college-basketball/events/", game_id, "/competitions/", game_id,"/competitors/") game_res <- httr::RETRY("GET", play_base_url) # Check the result check_status(game_res) game_resp <- game_res %>% httr::content(as = "text", encoding = "UTF-8") game_df <- jsonlite::fromJSON(game_resp)[["items"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% dplyr::rename("team_statistics_href" = "statistics.$ref") colnames(game_df) <- gsub(".\\$ref","_href", colnames(game_df)) game_df <- game_df %>% dplyr::rename( "team_id" = "id", "team_uid" = "uid") game_df$game_id <- game_id teams_df <- purrr::map_dfr(game_df$team_href, function(x){ res <- httr::RETRY("GET", x) # Check the result check_status(res) team_df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["againstTheSpreadRecords"]] <- NULL team_df[["oddsRecords"]] <- NULL team_df[["college"]] <- NULL team_df[["transactions"]] <- NULL team_df[["leaders"]] <- NULL team_df[["depthCharts"]] <- NULL team_df[["awards"]] <- NULL team_df[["events"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list,as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.rel..scoreboard.", "logos.rel..scoreboard..1", "logos.rel..scoreboard.2", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.rel..dark..1", "logos.lastUpdated.1", "logos.width.2", "logos.height.2", "logos.alt.2", "logos.rel..full..2", "logos.rel..scoreboard.", "logos.lastUpdated.2", "logos.width.3", "logos.height.3", "logos.alt.3", "logos.rel..full..3", "logos.lastUpdated.3", "X.ref", "X.ref.1", "X.ref.2"))) %>% janitor::clean_names() colnames(team_df)[1:13] <- paste0("team_",colnames(team_df)[1:13]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") %>% dplyr::left_join( game_df %>% dplyr::select( "game_id", "team_id", "team_uid", "order", "homeAway", "winner", "roster_href"), by = c("team_id" = "team_id", "team_uid" = "team_uid") ) }) team_ids <- teams_df$team_id ## Inputs ## game_id team_roster_df <- purrr::map_dfr(teams_df$team_id, function(x){ res <- httr::RETRY("GET", paste0(play_base_url, x, "/roster")) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_play_df <- jsonlite::fromJSON(resp)[["entries"]] raw_play_df <- raw_play_df %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% dplyr::mutate(team_id = x) %>% dplyr::select(-"period", -"forPlayerId", -"active") raw_play_df <- raw_play_df %>% dplyr::left_join(teams_df, by = c("team_id" = "team_id")) }) colnames(team_roster_df) <- gsub(".\\$ref","_href", colnames(team_roster_df)) athlete_roster_df <- purrr::map_dfr(team_roster_df$athlete_href, function(x){ res <- httr::RETRY("GET", x) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_play_df <- jsonlite::fromJSON(resp, flatten = TRUE) raw_play_df[['links']] <- NULL raw_play_df[['injuries']] <- NULL raw_play_df[['teams']] <- NULL raw_play_df[['team']] <- NULL raw_play_df[['college']] <- NULL raw_play_df[['proAthlete']] <- NULL raw_play_df[['statistics']] <- NULL raw_play_df[['notes']] <- NULL raw_play_df[['eventLog']] <- NULL raw_play_df[["$ref"]] <- NULL raw_play_df[["position"]][["$ref"]] <- NULL raw_play_df2 <- raw_play_df %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% as.data.frame() %>% dplyr::mutate(id = as.integer(.data$id)) %>% dplyr::rename( "athlete_id" = "id", "athlete_uid" = "uid", "athlete_guid" = "guid", "athlete_type" = "type", "athlete_display_name" = "displayName" ) raw_play_df2 <- raw_play_df2 %>% dplyr::left_join(team_roster_df, by = c("athlete_id" = "playerId")) }) colnames(athlete_roster_df) <- gsub(".\\$ref","_href", colnames(athlete_roster_df)) athlete_roster_df <- athlete_roster_df %>% janitor::clean_names() %>% dplyr::select(-dplyr::any_of(c( "athlete_href", "position_href", "statistics_href" ))) %>% dplyr::mutate_at(c( "game_id", "athlete_id", "team_id", "position_id", "status_id", "sdr", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WBB Game Roster Information from ESPN.com",Sys.time()) }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no game roster data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) return(athlete_roster_df) } #' Get women's college basketball conferences #' #' @author Saiem Gilani #' @return Returns a tibble #' #' |col_name |types | #' |:---------------------|:---------| #' |group_id |integer | #' |conference_short_name |character | #' |conference_uid |character | #' |conference_name |character | #' |conference_logo |character | #' |parent_group_id |integer | #' |conference_id |integer | #' #' @importFrom jsonlite fromJSON #' @importFrom janitor clean_names #' @importFrom dplyr select #' @import rvest #' @export #' @keywords WBB Conferences #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_conferences()) #' } espn_wbb_conferences <- function(){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) tryCatch( expr = { play_base_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/scoreboard/conferences?seasontype=2" res <- httr::RETRY("GET", play_base_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") conferences <- jsonlite::fromJSON(resp)[["conferences"]] %>% dplyr::select(-"subGroups") %>% janitor::clean_names() %>% dplyr::filter(!(.data$group_id %in% c(0,50))) %>% dplyr::mutate( group_id = as.integer(.data$group_id), conference_id = .data$group_id, parent_group_id = as.integer(.data$parent_group_id)) %>% dplyr::rename(dplyr::any_of(c( "conference_short_name" = "short_name", "conference_uid" = "uid", "conference_name" = "name", "conference_logo" = "logo" ))) %>% make_wehoop_data("ESPN WBB Conferences Information from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no conferences info available!")) }, warning = function(w) { }, finally = { } ) return(conferences) } #' Get ESPN women's college basketball team names and ids #' @author Saiem Gilani #' @param year Either numeric or character (YYYY) #' @return Returns a teams infomation data frame #' #' |col_name |types | #' |:---------------------|:---------| #' |team_id |integer | #' |abbreviation |character | #' |display_name |character | #' |short_name |character | #' |mascot |character | #' |nickname |character | #' |team |character | #' |color |character | #' |alternate_color |character | #' |logo |character | #' |logo_dark |character | #' |href |character | #' |conference_url |character | #' |group_id |integer | #' |conference_short_name |character | #' |conference_uid |character | #' |conference_name |character | #' |conference_logo |character | #' |parent_group_id |integer | #' |conference_id |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows row_number group_by mutate as_tibble ungroup #' @importFrom tidyr unnest unnest_wider everything pivot_wider #' @import rvest #' @export #' @keywords WBB Teams #' @family ESPN WBB Functions #' #' @examples #' \donttest{ #' try(espn_wbb_teams()) #' } espn_wbb_teams <- function(year = most_recent_wbb_season()){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) tryCatch( expr = { teams_base_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/teams?limit=1000" res <- httr::RETRY("GET", teams_base_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") leagues <- jsonlite::fromJSON(resp)[["sports"]][["leagues"]][[1]][['teams']][[1]][['team']] %>% dplyr::group_by(.data$id) %>% tidyr::unnest_wider("logos",names_sep = "_") %>% tidyr::unnest_wider("logos_href",names_sep = "_") %>% dplyr::select( -"logos_width", -"logos_height", -"logos_alt", -"logos_rel") %>% dplyr::ungroup() if ("records" %in% colnames(leagues)) { records <- leagues$record records <- records %>% tidyr::unnest_wider("items") %>% tidyr::unnest_wider("stats", names_sep = "_") %>% dplyr::mutate(row = dplyr::row_number()) stat <- records %>% dplyr::group_by(.data$row) %>% purrr::map_if(is.data.frame, list) stat <- lapply(stat$stats_1,function(x) x %>% purrr::map_if(is.data.frame,list) %>% dplyr::as_tibble()) s <- lapply(stat, function(x) { tidyr::pivot_wider(x) }) s <- tibble::tibble(g = s) stats <- s %>% unnest_wider("g") records <- dplyr::bind_cols(records %>% dplyr::select("summary"), stats) leagues <- leagues %>% dplyr::select( -dplyr::any_of("record") ) } league_drop_cols <- c("links", "isActive", "isAllStar", "uid", "slug") leagues <- leagues %>% dplyr::select(-dplyr::any_of(league_drop_cols)) teams <- leagues %>% dplyr::rename( "logo" = "logos_href_1", "logo_dark" = "logos_href_2", "mascot" = "name", "team" = "location", "team_id" = "id", "short_name" = "shortDisplayName", "alternate_color" = "alternateColor", "display_name" = "displayName") %>% dplyr::mutate(team_id = as.integer(.data$team_id)) conferences <- espn_wbb_conferences() # ---- Figuring out which teams are in which conference (32 calls) base_url <- "http://sports.core.api.espn.com/v2/sports/basketball/leagues/womens-college-basketball/seasons" conferences_base_url <- glue::glue("{base_url}/{year}/types/2/groups/50/children?limit=1000&lang=en&region=us") res <- httr::RETRY("GET", conferences_base_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") conf_items <- resp %>% jsonlite::fromJSON() %>% purrr::pluck("items") %>% data.frame() %>% dplyr::rename("href" = "X.ref") %>% dplyr::mutate( group_id = as.integer(stringr::str_extract(.data$href, "(?<=groups\\/)\\d+")), teams_url = paste0(base_url,"/", year, "/types/2/groups/", .data$group_id, "/teams?lang=en&region=us") ) conference_teams <- purrr::map_dfr(conf_items$teams_url, function(x){ res <- httr::RETRY("GET", x) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") conf_items <- resp %>% jsonlite::fromJSON() %>% purrr::pluck("items") %>% data.frame() %>% dplyr::rename("href" = "X.ref") %>% dplyr::mutate( conference_url = x, group_id = as.integer(stringr::str_extract(x, "(?<=groups\\/)\\d+")), team_id = as.integer(stringr::str_extract(.data$href, "(?<=teams\\/)\\d+")) ) return(conf_items) }) teams <- teams %>% dplyr::left_join(conference_teams, by = c("team_id" = "team_id")) %>% dplyr::left_join(conferences, by = c("group_id" = "group_id")) %>% dplyr::mutate( team_id = as.integer(.data$team_id), parent_group_id = as.integer(.data$parent_group_id)) %>% make_wehoop_data("ESPN WBB Teams Information from ESPN.com", Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no teams data available!")) }, warning = function(w) { }, finally = { } ) return(teams) } #' **Parse ESPN schedule, helper function** #' #' @param group The ESPN conference group. Most helpful ones: #' * 50 - Regular season/NIT #' * 100 - NCAA Tournament #' @param season_dates Either numeric or character #' @return Returns a tibble #' @import utils #' @importFrom dplyr select rename any_of mutate #' @importFrom jsonlite fromJSON #' @importFrom tidyr unnest_wider unchop hoist #' @importFrom glue glue #' @import rvest #' @noRd parse_espn_wbb_scoreboard <- function(group, season_dates) { schedule_api <- glue::glue( "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/scoreboard?groups={group}&limit=1000&dates={season_dates}" ) tryCatch( expr = { res <- httr::RETRY("GET", schedule_api) # Check the result check_status(res) raw_sched <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON( simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE ) wbb_data <- raw_sched[["events"]] %>% tibble::tibble(data = .data$.) %>% tidyr::unnest_wider("data") %>% tidyr::unchop("competitions") %>% dplyr::select( -"id", -"uid", -"date", -"status") %>% tidyr::unnest_wider("competitions") %>% dplyr::rename( "matchup" = "name", "matchup_short" = "shortName", "game_id" = "id", "game_uid" = "uid", "game_date" = "date" ) %>% tidyr::hoist("status", status_name = list("type", "name")) %>% dplyr::select(!dplyr::any_of( c( "timeValid", "neutralSite", "conferenceCompetition", "recent", "venue", "type" ) )) %>% tidyr::unnest_wider("season", names_sep = "_") %>% dplyr::rename("season" = "season_year") %>% dplyr::select(-dplyr::any_of("status")) wbb_data <- wbb_data %>% dplyr::mutate( game_date_time = lubridate::ymd_hm(substr(.data$game_date, 1, nchar(.data$game_date) - 1)) %>% lubridate::with_tz(tzone = "America/New_York"), game_date = as.Date(substr(.data$game_date_time, 1, 10))) wbb_data <- wbb_data %>% tidyr::hoist( "competitors", homeAway = list(1,"homeAway")) wbb_data <- wbb_data %>% tidyr::hoist( "competitors", team1_team_name = list(1, "team", "name"), team1_team_logo = list(1, "team", "logo"), team1_team_abb = list(1, "team", "abbreviation"), team1_team_id = list(1, "team", "id"), team1_team_location = list(1, "team", "location"), team1_team_full = list(1, "team", "displayName"), team1_team_color = list(1, "team", "color"), team1_score = list(1, "score"), team1_win = list(1, "winner"), team1_record = list(1, "records", 1, "summary"), # away team team2_team_name = list(2, "team", "name"), team2_team_logo = list(2, "team", "logo"), team2_team_abb = list(2, "team", "abbreviation"), team2_team_id = list(2, "team", "id"), team2_team_location = list(2, "team", "location"), team2_team_full = list(2, "team", "displayName"), team2_team_color = list(2, "team", "color"), team2_score = list(2, "score"), team2_win = list(2, "winner"), team2_record = list(2, "records", 1, "summary")) wbb_data <- wbb_data %>% dplyr::mutate( home_team_name = ifelse(.data$homeAway == "home", .data$team1_team_name, .data$team2_team_name), home_team_logo = ifelse(.data$homeAway == "home", .data$team1_team_logo, .data$team2_team_logo), home_team_abb = ifelse(.data$homeAway == "home", .data$team1_team_abb, .data$team2_team_abb), home_team_id = ifelse(.data$homeAway == "home", .data$team1_team_id, .data$team2_team_id), home_team_location = ifelse(.data$homeAway == "home", .data$team1_team_location, .data$team2_team_location), home_team_full_name = ifelse(.data$homeAway == "home", .data$team1_team_full, .data$team2_team_full), home_team_color = ifelse(.data$homeAway == "home", .data$team1_team_color, .data$team2_team_color), home_score = ifelse(.data$homeAway == "home", .data$team1_score, .data$team2_score), home_win = ifelse(.data$homeAway == "home", .data$team1_win, .data$team2_win), home_record = ifelse(.data$homeAway == "home", .data$team1_record, .data$team2_record), away_team_name = ifelse(.data$homeAway == "away", .data$team1_team_name, .data$team2_team_name), away_team_logo = ifelse(.data$homeAway == "away", .data$team1_team_logo, .data$team2_team_logo), away_team_abb = ifelse(.data$homeAway == "away", .data$team1_team_abb, .data$team2_team_abb), away_team_id = ifelse(.data$homeAway == "away", .data$team1_team_id, .data$team2_team_id), away_team_location = ifelse(.data$homeAway == "away", .data$team1_team_location, .data$team2_team_location), away_team_full_name = ifelse(.data$homeAway == "away", .data$team1_team_full, .data$team2_team_full), away_team_color = ifelse(.data$homeAway == "away", .data$team1_team_color, .data$team2_team_color), away_score = ifelse(.data$homeAway == "away", .data$team1_score, .data$team2_score), away_win = ifelse(.data$homeAway == "away", .data$team1_win, .data$team2_win), away_record = ifelse(.data$homeAway == "away", .data$team1_record, .data$team2_record) ) wbb_data <- wbb_data %>% dplyr::mutate_at(c( "game_id", "home_team_id", "home_win", "away_team_id", "away_win", "home_score", "away_score"), as.integer) wbb_data <- wbb_data %>% dplyr::select(-dplyr::any_of(dplyr::starts_with("team1")), -dplyr::any_of(dplyr::starts_with("team2")), -dplyr::any_of(c("homeAway"))) if ("leaders" %in% names(wbb_data)) { schedule_out <- wbb_data %>% tidyr::hoist( "leaders", # points points_leader_points = list(1, "leaders", 1, "value"), points_leader_stat = list(1, "leaders", 1, "displayValue"), points_leader_name = list(1, "leaders", 1, "athlete", "displayName"), points_leader_shortname = list(1, "leaders", 1, "athlete", "shortName"), points_leader_headshot = list(1, "leaders", 1, "athlete", "headshot"), points_leader_team_id = list(1, "leaders", 1, "team", "id"), points_leader_pos = list(1, "leaders", 1, "athlete", "position", "abbreviation"), # rebounds rebounds_leader_rebounds = list(2, "leaders", 1, "value"), rebounds_leader_stat = list(2, "leaders", 1, "displayValue"), rebounds_leader_name = list(2, "leaders", 1, "athlete", "displayName"), rebounds_leader_shortname = list(2, "leaders", 1, "athlete", "shortName"), rebounds_leader_headshot = list(2, "leaders", 1, "athlete", "headshot"), rebounds_leader_team_id = list(2, "leaders", 1, "team", "id"), rebounds_leader_pos = list(2, "leaders", 1, "athlete", "position", "abbreviation"), # assists assists_leader_assists = list(3, "leaders", 1, "value"), assists_leader_stat = list(3, "leaders", 1, "displayValue"), assists_leader_name = list(3, "leaders", 1, "athlete", "displayName"), assists_leader_shortname = list(3, "leaders", 1, "athlete", "shortName"), assists_leader_headshot = list(3, "leaders", 1, "athlete", "headshot"), assists_leader_team_id = list(3, "leaders", 1, "team", "id"), assists_leader_pos = list(3, "leaders", 1, "athlete", "position", "abbreviation"), ) if ("broadcasts" %in% names(schedule_out)) { schedule_out %>% tidyr::hoist( "broadcasts", broadcast_market = list(1, "market"), broadcast_name = list(1, "names", 1)) %>% dplyr::select(!where(is.list)) %>% janitor::clean_names() %>% make_wehoop_data("ESPN WBB Scoreboard Information from ESPN.com",Sys.time()) } else { schedule_out %>% janitor::clean_names() %>% make_wehoop_data("ESPN WBB Scoreboard Information from ESPN.com",Sys.time()) } } else { if ("broadcasts" %in% names(wbb_data)) { wbb_data %>% tidyr::hoist( "broadcasts", broadcast_market = list(1, "market"), broadcast_name = list(1, "names", 1)) %>% dplyr::select(!where(is.list)) %>% janitor::clean_names() %>% make_wehoop_data("ESPN WBB Scoreboard Information from ESPN.com",Sys.time()) } else { wbb_data %>% dplyr::select(!where(is.list)) %>% janitor::clean_names() %>% make_wehoop_data("ESPN WBB Scoreboard Information from ESPN.com",Sys.time()) } } }, error = function(e) { }, warning = function(w) { }, finally = { } ) } #' **Get ESPN women's college basketball schedule for a specific year** #' #' @param season Either numeric or character #' @return Returns a tibble #' #' |col_name |types | #' |:-------------------|:---------| #' |matchup |character | #' |matchup_short |character | #' |season |integer | #' |season_type |integer | #' |season_slug |character | #' |game_id |integer | #' |game_uid |character | #' |game_date |Date | #' |attendance |integer | #' |status_name |character | #' |broadcast_market |character | #' |broadcast_name |character | #' |start_date |character | #' |game_date_time |POSIXct | #' |home_team_name |character | #' |home_team_logo |character | #' |home_team_abb |character | #' |home_team_id |integer | #' |home_team_location |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_score |integer | #' |home_win |integer | #' |home_record |character | #' |away_team_name |character | #' |away_team_logo |character | #' |away_team_abb |character | #' |away_team_id |integer | #' |away_team_location |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_score |integer | #' |away_win |integer | #' |away_record |character | #' #' @import utils #' @importFrom dplyr select rename any_of mutate #' @importFrom jsonlite fromJSON #' @importFrom tidyr unnest_wider unchop hoist #' @importFrom glue glue #' @importFrom purrr map2_dfr possibly quietly #' @importFrom lubridate with_tz ymd_hm #' @import rvest #' @export #' @keywords WBB Scoreboard #' @family ESPN WBB Functions #' @examples #' #' # Get schedule from date 2022-11-15 #' \donttest{ #' try(espn_wbb_scoreboard (season = "20230225")) #' } espn_wbb_scoreboard <- function(season) { max_year <- substr(Sys.Date(), 1, 4) if (!(as.integer(substr(season, 1, 4)) > 2001)) { message(paste("Error: Season must be between 2001 and", max_year + 1)) } # year > 2000 season <- as.character(season) season_dates <- season # check for regular and postseason games scoreboard_df <- purrr::map2_dfr(c("50"), rep(season, 4), parse_espn_wbb_scoreboard) if (!nrow(scoreboard_df)) { message(glue::glue( "{Sys.time()}: Invalid arguments or no scoreboard data available!" )) } return(scoreboard_df) } #' @import utils utils::globalVariables(c("where")) #' Get women's college basketball AP and Coaches poll rankings #' #' @author Saiem Gilani #' @return Returns a tibble #' #' |col_name |types | #' |:------------------------|:---------| #' |id |integer | #' |name |character | #' |short_name |character | #' |type |character | #' |headline |character | #' |short_headline |character | #' |current |integer | #' |previous |integer | #' |points |numeric | #' |first_place_votes |integer | #' |trend |character | #' |date |character | #' |last_updated |character | #' |record_summary |character | #' |team_id |integer | #' |team_uid |character | #' |team_location |character | #' |team_name |character | #' |team_nickname |character | #' |team_abbreviation |character | #' |team_color |character | #' |team_logo |character | #' |occurrence_number |integer | #' |occurrence_type |character | #' |occurrence_last |logical | #' |occurrence_value |character | #' |occurrence_display_value |character | #' |season_year |integer | #' |season_start_date |character | #' |season_end_date |character | #' |season_display_name |character | #' |season_type_type |integer | #' |season_type_name |character | #' |season_type_abbreviation |character | #' |first_occurrence_type |character | #' |first_occurrence_value |character | #' #' @importFrom dplyr %>% bind_rows arrange select #' @importFrom jsonlite fromJSON #' @importFrom tidyr unnest #' @import rvest #' @export #' @keywords WBB Rankings #' @family ESPN WBB Functions #' @examples #' # Get current AP and Coaches Poll rankings #' \donttest{ #' try(espn_wbb_rankings()) #' } espn_wbb_rankings <- function(){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) ranks_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/womens-college-basketball/rankings?lang=en&region=us&groups=50" res <- httr::RETRY("GET", ranks_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") tryCatch( expr = { ranks_df <- jsonlite::fromJSON(resp,flatten = TRUE)[['rankings']] ranks_top25 <- ranks_df %>% dplyr::select( -"date", -"lastUpdated") %>% tidyr::unnest("ranks", names_repair = "minimal") ranks_others <- ranks_df %>% dplyr::select( -"date", -"lastUpdated") %>% tidyr::unnest("others", names_repair = "minimal") ranks_dropped_out <- ranks_df %>% dplyr::select( -"date", -"lastUpdated") %>% tidyr::unnest("droppedOut", names_repair = "minimal") ranks <- dplyr::bind_rows(ranks_top25, ranks_others, ranks_dropped_out) drop_cols <- c( "$ref", "team.links","season.powerIndexes.$ref", "season.powerIndexLeaders.$ref", "season.athletes.$ref", "season.leaders.$ref","season.powerIndexLeaders.$ref", "others","droppedOut","ranks" ) ranks <- ranks %>% dplyr::select(-dplyr::any_of(drop_cols)) ranks <- ranks %>% dplyr::arrange(.data$name, -.data$points) %>% janitor::clean_names() %>% dplyr::mutate_at(c( "id", "team_id" ), as.integer) %>% make_wehoop_data("ESPN WBB Rankings Information from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no rankings data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(ranks) } #' Get ESPN women's college basketball standings #' #' @param year Either numeric or character (YYYY) #' @return Returns a tibble #' #' |col_name |types | #' |:---------------------------------|:---------| #' |team_id |integer | #' |team |character | #' |avgpointsagainst |numeric | #' |avgpointsfor |numeric | #' |gamesbehind |numeric | #' |leaguewinpercent |numeric | #' |losses |numeric | #' |playoffseed |numeric | #' |pointsagainst |numeric | #' |pointsfor |numeric | #' |streak |numeric | #' |winpercent |numeric | #' |wins |numeric | #' |total |character | #' |home_avgpointsagainst |numeric | #' |home_avgpointsfor |numeric | #' |home_gamesbehind |numeric | #' |home_leaguewinpercent |numeric | #' |home_losses |numeric | #' |home_playoffseed |numeric | #' |home_pointsagainst |numeric | #' |home_pointsfor |numeric | #' |home_streak |numeric | #' |home_winpercent |numeric | #' |home_wins |numeric | #' |home |character | #' |road_avgpointsagainst |numeric | #' |road_avgpointsfor |numeric | #' |road_gamesbehind |numeric | #' |road_leaguewinpercent |numeric | #' |road_losses |numeric | #' |road_playoffseed |numeric | #' |road_pointsagainst |numeric | #' |road_pointsfor |numeric | #' |road_streak |numeric | #' |road_winpercent |numeric | #' |road_wins |numeric | #' |road |character | #' |vsaprankedteams_avgpointsagainst |numeric | #' |vsaprankedteams_avgpointsfor |numeric | #' |vsaprankedteams_gamesbehind |numeric | #' |vsaprankedteams_leaguewinpercent |numeric | #' |vsaprankedteams_losses |numeric | #' |vsaprankedteams_playoffseed |numeric | #' |vsaprankedteams_pointsagainst |numeric | #' |vsaprankedteams_pointsfor |numeric | #' |vsaprankedteams_streak |numeric | #' |vsaprankedteams_winpercent |numeric | #' |vsaprankedteams_wins |numeric | #' |vsaprankedteams |character | #' |vsusarankedteams_avgpointsagainst |numeric | #' |vsusarankedteams_avgpointsfor |numeric | #' |vsusarankedteams_gamesbehind |numeric | #' |vsusarankedteams_leaguewinpercent |numeric | #' |vsusarankedteams_losses |numeric | #' |vsusarankedteams_playoffseed |numeric | #' |vsusarankedteams_pointsagainst |numeric | #' |vsusarankedteams_pointsfor |numeric | #' |vsusarankedteams_streak |numeric | #' |vsusarankedteams_winpercent |numeric | #' |vsusarankedteams_wins |numeric | #' |vsusarankedteams |character | #' |vsconf_avgpointsagainst |numeric | #' |vsconf_avgpointsfor |numeric | #' |vsconf_gamesbehind |numeric | #' |vsconf_leaguewinpercent |numeric | #' |vsconf_losses |numeric | #' |vsconf_playoffseed |numeric | #' |vsconf_pointsagainst |numeric | #' |vsconf_pointsfor |numeric | #' |vsconf_streak |numeric | #' |vsconf_winpercent |numeric | #' |vsconf_wins |numeric | #' |vsconf |character | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr select rename #' @importFrom tidyr pivot_wider #' @export #' @keywords WBB Standings #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_standings(2021)) #' } espn_wbb_standings <- function(year){ standings_url <- "https://site.web.api.espn.com/apis/v2/sports/basketball/womens-college-basketball/standings?region=us&lang=en&contentorigin=espn&type=0&level=1&sort=winpercent%3Adesc%2Cwins%3Adesc%2Cgamesbehind%3Aasc&" ## Inputs ## year full_url <- paste0(standings_url, "season=", year) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) tryCatch( expr = { resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_standings <- jsonlite::fromJSON(resp)[["standings"]] #Create a dataframe of all WBB teams by extracting from the raw_standings file teams <- raw_standings[["entries"]][["team"]] teams <- teams %>% dplyr::select( "id", "displayName") %>% dplyr::rename( "team_id" = "id", "team" = "displayName") #creating a dataframe of the WNBA raw standings table from ESPN standings_df <- raw_standings[["entries"]][["stats"]] standings_data <- data.table::rbindlist(standings_df, fill = TRUE, idcol = T) #Use the following code to replace NA's in the dataframe with the correct corresponding values and removing all unnecessary columns standings_data$value <- ifelse(is.na(standings_data$value) & !is.na(standings_data$summary), standings_data$summary, standings_data$value) standings_data <- standings_data %>% dplyr::select( ".id", "type", "value") #Use pivot_wider to transpose the dataframe so that we now have a standings row for each team standings_data <- standings_data %>% tidyr::pivot_wider(names_from = "type", values_from = "value") standings_data <- standings_data %>% dplyr::select(-".id") #joining the 2 dataframes together to create a standings table standings <- cbind(teams, standings_data) %>% dplyr::mutate(team_id = as.integer(.data$team_id)) standings <- standings %>% dplyr::mutate_at(c( "avgpointsagainst", "avgpointsfor", "gamesbehind", "leaguewinpercent", "losses", "playoffseed", "pointsagainst", "pointsfor", "streak", "winpercent", "wins", "home_avgpointsagainst", "home_avgpointsfor", "home_gamesbehind", "home_leaguewinpercent", "home_losses", "home_playoffseed", "home_pointsagainst", "home_pointsfor", "home_streak", "home_winpercent", "home_wins", "road_avgpointsagainst", "road_avgpointsfor", "road_gamesbehind", "road_leaguewinpercent", "road_losses", "road_playoffseed", "road_pointsagainst", "road_pointsfor", "road_streak", "road_winpercent", "road_wins", "vsaprankedteams_avgpointsagainst", "vsaprankedteams_avgpointsfor", "vsaprankedteams_gamesbehind", "vsaprankedteams_leaguewinpercent", "vsaprankedteams_losses", "vsaprankedteams_playoffseed", "vsaprankedteams_pointsagainst", "vsaprankedteams_pointsfor", "vsaprankedteams_streak", "vsaprankedteams_winpercent", "vsaprankedteams_wins", "vsusarankedteams_avgpointsagainst", "vsusarankedteams_avgpointsfor", "vsusarankedteams_gamesbehind", "vsusarankedteams_leaguewinpercent", "vsusarankedteams_losses", "vsusarankedteams_playoffseed", "vsusarankedteams_pointsagainst", "vsusarankedteams_pointsfor", "vsusarankedteams_streak", "vsusarankedteams_winpercent", "vsusarankedteams_wins", "vsconf_avgpointsagainst", "vsconf_avgpointsfor", "vsconf_gamesbehind", "vsconf_leaguewinpercent", "vsconf_losses", "vsconf_playoffseed", "vsconf_pointsagainst", "vsconf_pointsfor", "vsconf_streak", "vsconf_winpercent", "vsconf_wins" ), as.numeric) %>% make_wehoop_data("ESPN WBB Standings Information from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no standings data available!")) }, warning = function(w) { }, finally = { } ) return(standings) } #' @title #' **Get ESPN women's college basketball team stats data** #' @author Saiem Gilani #' @param team_id Team ID #' @param year Year #' @param season_type (character, default: regular): Season type - regular or postseason #' @param total (boolean, default: FALSE): Totals #' @return Returns a tibble with the team stats data #' #' |col_name |types | #' |:-----------------------------------------------|:---------| #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_nickname |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_is_active |logical | #' |team_is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' |defensive_blocks |numeric | #' |defensive_defensive_rebounds |numeric | #' |defensive_steals |numeric | #' |defensive_turnover_points |numeric | #' |defensive_avg_defensive_rebounds |numeric | #' |defensive_avg_blocks |numeric | #' |defensive_avg_steals |numeric | #' |general_disqualifications |numeric | #' |general_flagrant_fouls |numeric | #' |general_fouls |numeric | #' |general_ejections |numeric | #' |general_technical_fouls |numeric | #' |general_rebounds |numeric | #' |general_minutes |numeric | #' |general_avg_minutes |numeric | #' |general_fantasy_rating |numeric | #' |general_avg_rebounds |numeric | #' |general_avg_fouls |numeric | #' |general_avg_flagrant_fouls |numeric | #' |general_avg_technical_fouls |numeric | #' |general_avg_ejections |numeric | #' |general_avg_disqualifications |numeric | #' |general_assist_turnover_ratio |numeric | #' |general_steal_foul_ratio |numeric | #' |general_block_foul_ratio |numeric | #' |general_avg_team_rebounds |numeric | #' |general_total_rebounds |numeric | #' |general_total_technical_fouls |numeric | #' |general_team_assist_turnover_ratio |numeric | #' |general_team_rebounds |numeric | #' |general_steal_turnover_ratio |numeric | #' |general_games_played |numeric | #' |general_games_started |numeric | #' |general_double_double |numeric | #' |general_triple_double |numeric | #' |offensive_assists |numeric | #' |offensive_field_goals |numeric | #' |offensive_field_goals_attempted |numeric | #' |offensive_field_goals_made |numeric | #' |offensive_field_goal_pct |numeric | #' |offensive_free_throws |numeric | #' |offensive_free_throw_pct |numeric | #' |offensive_free_throws_attempted |numeric | #' |offensive_free_throws_made |numeric | #' |offensive_offensive_rebounds |numeric | #' |offensive_points |numeric | #' |offensive_turnovers |numeric | #' |offensive_three_point_field_goals_attempted |numeric | #' |offensive_three_point_field_goals_made |numeric | #' |offensive_team_turnovers |numeric | #' |offensive_total_turnovers |numeric | #' |offensive_fast_break_points |numeric | #' |offensive_avg_field_goals_made |numeric | #' |offensive_avg_field_goals_attempted |numeric | #' |offensive_avg_three_point_field_goals_made |numeric | #' |offensive_avg_three_point_field_goals_attempted |numeric | #' |offensive_avg_free_throws_made |numeric | #' |offensive_avg_free_throws_attempted |numeric | #' |offensive_avg_points |numeric | #' |offensive_avg_offensive_rebounds |numeric | #' |offensive_avg_assists |numeric | #' |offensive_avg_turnovers |numeric | #' |offensive_offensive_rebound_pct |numeric | #' |offensive_estimated_possessions |numeric | #' |offensive_avg_estimated_possessions |numeric | #' |offensive_points_per_estimated_possessions |numeric | #' |offensive_avg_team_turnovers |numeric | #' |offensive_avg_total_turnovers |numeric | #' |offensive_three_point_field_goal_pct |numeric | #' |offensive_two_point_field_goals_made |numeric | #' |offensive_two_point_field_goals_attempted |numeric | #' |offensive_avg_two_point_field_goals_made |numeric | #' |offensive_avg_two_point_field_goals_attempted |numeric | #' |offensive_two_point_field_goal_pct |numeric | #' |offensive_shooting_efficiency |numeric | #' |offensive_scoring_efficiency |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @export #' @keywords WBB Team Stats #' @family ESPN WBB Functions #' @examples #' \donttest{ #' try(espn_wbb_team_stats(team_id = 52, year = 2020)) #' } espn_wbb_team_stats <- function( team_id, year, season_type = 'regular', total = FALSE ){ if (!(tolower(season_type) %in% c("regular","postseason"))) { # Check if season_type is appropriate, if not regular cli::cli_abort("Enter valid season_type: regular or postseason") } s_type <- ifelse(season_type == "postseason", 3, 2) base_url <- "https://sports.core.api.espn.com/v2/sports/basketball/leagues/womens-college-basketball/seasons/" totals <- ifelse(total == TRUE, 0, "") full_url <- paste0( base_url, year, '/types/',s_type, '/teams/',team_id, '/statistics/', totals ) df <- data.frame() tryCatch( expr = { # Create the GET request and set response as res res <- httr::RETRY("GET", full_url) # Check the result check_status(res) # Get the content and return result as data.frame df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() team_url <- df[["team"]][["$ref"]] # Create the GET request and set response as res team_res <- httr::RETRY("GET", team_url) # Check the result check_status(team_res) # Get the content and return result as data.frame team_df <- team_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["record"]] <- NULL team_df[["college"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list,as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.lastUpdated.1", "X.ref", "X.ref.1"))) %>% janitor::clean_names() colnames(team_df)[1:15] <- paste0("team_",colnames(team_df)[1:15]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") df <- df %>% purrr::pluck("splits") %>% purrr::pluck("categories") %>% tidyr::unnest("stats", names_sep = "_") df <- df %>% dplyr::mutate( stats_category_name = glue::glue("{.data$name}_{.data$stats_name}")) %>% dplyr::select( "stats_category_name", "stats_value") %>% tidyr::pivot_wider( names_from = "stats_category_name", values_from = "stats_value", values_fn = dplyr::first) %>% janitor::clean_names() df <- team_df %>% dplyr::bind_cols(df) df <- df %>% dplyr::mutate_at(c( "team_id", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WBB Team Season Stats from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}:Invalid arguments or no team season stats data available!")) }, warning = function(w) { }, finally = { } ) return(df) } #' @title #' **Get ESPN women's college basketball player stats data** #' @author Saiem Gilani #' @param athlete_id Athlete ID #' @param year Year #' @param season_type (character, default: regular): Season type - regular or postseason #' @param total (boolean, default: FALSE): Totals #' @return Returns a tibble with the player stats data #' #' |col_name |types | #' |:-----------------------------------------------|:---------| #' |athlete_id |integer | #' |athlete_uid |character | #' |athlete_guid |character | #' |athlete_type |character | #' |sdr |integer | #' |first_name |character | #' |last_name |character | #' |full_name |character | #' |display_name |character | #' |short_name |character | #' |height |numeric | #' |display_height |character | #' |birth_place_city |character | #' |birth_place_state |character | #' |birth_place_country |character | #' |slug |character | #' |headshot_href |character | #' |headshot_alt |character | #' |jersey |character | #' |position_id |integer | #' |position_name |character | #' |position_display_name |character | #' |position_abbreviation |character | #' |position_leaf |logical | #' |linked |logical | #' |experience_years |integer | #' |experience_display_value |character | #' |experience_abbreviation |character | #' |active |logical | #' |status_id |integer | #' |status_name |character | #' |status_type |character | #' |status_abbreviation |character | #' |defensive_blocks |numeric | #' |defensive_defensive_rebounds |numeric | #' |defensive_steals |numeric | #' |defensive_turnover_points |numeric | #' |defensive_avg_defensive_rebounds |numeric | #' |defensive_avg_blocks |numeric | #' |defensive_avg_steals |numeric | #' |general_disqualifications |numeric | #' |general_flagrant_fouls |numeric | #' |general_fouls |numeric | #' |general_per |numeric | #' |general_ejections |numeric | #' |general_technical_fouls |numeric | #' |general_rebounds |numeric | #' |general_minutes |numeric | #' |general_avg_minutes |numeric | #' |general_fantasy_rating |numeric | #' |general_plus_minus |numeric | #' |general_avg_rebounds |numeric | #' |general_avg_fouls |numeric | #' |general_avg_flagrant_fouls |numeric | #' |general_avg_technical_fouls |numeric | #' |general_avg_ejections |numeric | #' |general_avg_disqualifications |numeric | #' |general_assist_turnover_ratio |numeric | #' |general_steal_foul_ratio |numeric | #' |general_block_foul_ratio |numeric | #' |general_avg_team_rebounds |numeric | #' |general_total_rebounds |numeric | #' |general_total_technical_fouls |numeric | #' |general_steal_turnover_ratio |numeric | #' |general_games_played |numeric | #' |general_games_started |numeric | #' |general_double_double |numeric | #' |general_triple_double |numeric | #' |offensive_assists |numeric | #' |offensive_field_goals |numeric | #' |offensive_field_goals_attempted |numeric | #' |offensive_field_goals_made |numeric | #' |offensive_field_goal_pct |numeric | #' |offensive_free_throws |numeric | #' |offensive_free_throw_pct |numeric | #' |offensive_free_throws_attempted |numeric | #' |offensive_free_throws_made |numeric | #' |offensive_offensive_rebounds |numeric | #' |offensive_points |numeric | #' |offensive_turnovers |numeric | #' |offensive_three_point_field_goals_attempted |numeric | #' |offensive_three_point_field_goals_made |numeric | #' |offensive_total_turnovers |numeric | #' |offensive_points_in_paint |numeric | #' |offensive_fast_break_points |numeric | #' |offensive_avg_field_goals_made |numeric | #' |offensive_avg_field_goals_attempted |numeric | #' |offensive_avg_three_point_field_goals_made |numeric | #' |offensive_avg_three_point_field_goals_attempted |numeric | #' |offensive_avg_free_throws_made |numeric | #' |offensive_avg_free_throws_attempted |numeric | #' |offensive_avg_points |numeric | #' |offensive_avg_offensive_rebounds |numeric | #' |offensive_avg_assists |numeric | #' |offensive_avg_turnovers |numeric | #' |offensive_offensive_rebound_pct |numeric | #' |offensive_estimated_possessions |numeric | #' |offensive_avg_estimated_possessions |numeric | #' |offensive_points_per_estimated_possessions |numeric | #' |offensive_avg_team_turnovers |numeric | #' |offensive_avg_total_turnovers |numeric | #' |offensive_three_point_field_goal_pct |numeric | #' |offensive_two_point_field_goals_made |numeric | #' |offensive_two_point_field_goals_attempted |numeric | #' |offensive_avg_two_point_field_goals_made |numeric | #' |offensive_avg_two_point_field_goals_attempted |numeric | #' |offensive_two_point_field_goal_pct |numeric | #' |offensive_shooting_efficiency |numeric | #' |offensive_scoring_efficiency |numeric | #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_nickname |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_is_active |logical | #' |team_is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' #' @export #' @keywords WBB Player Stats #' @family ESPN WBB Functions #' #' @examples #' \donttest{ #' try(espn_wbb_player_stats(athlete_id = 2984250, year = 2022)) #' } espn_wbb_player_stats <- function( athlete_id, year, season_type = 'regular', total = FALSE ){ if (!(tolower(season_type) %in% c("regular","postseason"))) { # Check if season_type is appropriate, if not regular cli::cli_abort("Enter valid season_type: regular or postseason") } s_type <- ifelse(season_type == "postseason", 3, 2) base_url <- "https://sports.core.api.espn.com/v2/sports/basketball/leagues/womens-college-basketball/seasons/" totals <- ifelse(total == TRUE, 0, "") full_url <- paste0( base_url, year, '/types/',s_type, '/athletes/', athlete_id, '/statistics/', totals ) athlete_url <- paste0( base_url, year, '/athletes/', athlete_id ) df <- data.frame() tryCatch( expr = { # Create the GET request and set response as res res <- httr::RETRY("GET", full_url) # Check the result check_status(res) # Create the GET request and set response as res athlete_res <- httr::RETRY("GET", athlete_url) # Check the result check_status(athlete_res) athlete_df <- athlete_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_url <- athlete_df[["team"]][["$ref"]] # Create the GET request and set response as res team_res <- httr::RETRY("GET", team_url) # Check the result check_status(team_res) team_df <- team_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["record"]] <- NULL team_df[["college"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list,as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.lastUpdated.1", "X.ref", "X.ref.1"))) %>% janitor::clean_names() colnames(team_df)[1:15] <- paste0("team_",colnames(team_df)[1:15]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") athlete_df[["links"]] <- NULL athlete_df[["injuries"]] <- NULL athlete_df <- athlete_df %>% purrr::map_if(is.list, as.data.frame) %>% tibble::tibble(data = .data$.) athlete_df <- athlete_df$data %>% as.data.frame() %>% dplyr::select(-dplyr::any_of(c("X.ref","X.ref.1","X.ref.2","X.ref.3","X.ref.4","X.ref.5","position.X.ref"))) %>% janitor::clean_names() %>% dplyr::rename( "athlete_id" = "id", "athlete_uid" = "uid", "athlete_guid" = "guid", "athlete_type" = "type") # Get the content and return result as data.frame df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() %>% purrr::pluck("splits") %>% purrr::pluck("categories") %>% tidyr::unnest("stats", names_sep = "_") df <- df %>% dplyr::mutate( stats_category_name = glue::glue("{.data$name}_{.data$stats_name}")) %>% dplyr::select( "stats_category_name", "stats_value") %>% tidyr::pivot_wider( names_from = "stats_category_name", values_from = "stats_value", values_fn = dplyr::first) %>% janitor::clean_names() df <- athlete_df %>% dplyr::bind_cols(df) %>% dplyr::bind_cols(team_df) df <- df %>% dplyr::mutate_at(c( "athlete_id", "team_id", "position_id", "status_id", "sdr", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WBB Player Season Stats from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}:Invalid arguments or no player season stats data available!")) }, warning = function(w) { }, finally = { } ) return(df) } #' **Parse ESPN WBB PBP, helper function** #' @param resp Response object from the ESPN WBB game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wbb_pbp <- function(resp){ game_json <- resp %>% jsonlite::fromJSON() pbp_source <- game_json[["header"]][["competitions"]][["playByPlaySource"]] plays <- game_json %>% purrr::pluck("plays") %>% dplyr::as_tibble() if (pbp_source != "none" && nrow(plays) > 10) { homeAway1 <- jsonlite::fromJSON(resp)[['header']][['competitions']][['competitors']][[1]][['homeAway']][1] gameId <- as.integer(game_json[["header"]][["id"]]) season <- game_json[['header']][['season']][['year']] season_type <- game_json[['header']][['season']][['type']] game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) id_vars <- data.frame() if (homeAway1 == "home") { homeTeamId = as.integer(game_json[["header"]][["competitions"]][["competitors"]][[1]][['team']][['id']] %>% purrr::pluck(1, .default = NA_integer_)) homeTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(1, .default = NA_character_) homeTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(1, .default = NA_character_) homeTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(1, .default = NA_character_) homeTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(1, .default = NA_character_) homeTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(1, .default = NA_character_)) homeTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(1, .default = NA_character_) homeTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(1, .default = NA_character_) awayTeamId = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['team']][['id']] %>% purrr::pluck(2, .default = NA_integer_)) awayTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(2, .default = NA_character_) awayTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(2, .default = NA_character_) awayTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(2, .default = NA_character_) awayTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) awayTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(2, .default = NA_integer_)) awayTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(2, .default = NA_character_) awayTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(2, .default = NA_character_) id_vars <- data.frame( homeTeamId, homeTeamMascot, homeTeamName, homeTeamAbbrev, homeTeamLogo, homeTeamLogoDark, homeTeamFullName, homeTeamColor, homeTeamAlternateColor, homeTeamScore, homeTeamWinner, homeTeamRecord, awayTeamId, awayTeamMascot, awayTeamName, awayTeamAbbrev, awayTeamLogo, awayTeamLogoDark, awayTeamFullName, awayTeamColor, awayTeamAlternateColor, awayTeamScore, awayTeamWinner, awayTeamRecord ) } else { awayTeamId = as.integer(game_json[["header"]][["competitions"]][["competitors"]][[1]][['team']][['id']] %>% purrr::pluck(1, .default = NA_integer_)) awayTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(1, .default = NA_character_) awayTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(1, .default = NA_character_) awayTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(2, .default = NA_character_) awayTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(1, .default = NA_integer_)) awayTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(1, .default = NA_character_) awayTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(1, .default = NA_character_) homeTeamId = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['team']][['id']] %>% purrr::pluck(2, .default = NA_integer_)) homeTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(2, .default = NA_character_) homeTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(2, .default = NA_character_) homeTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(2, .default = NA_character_) homeTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(2, .default = NA_integer_)) homeTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(2, .default = NA_character_) homeTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(2, .default = NA_character_) id_vars <- data.frame( homeTeamId, homeTeamMascot, homeTeamName, homeTeamAbbrev, homeTeamLogo, homeTeamLogoDark, homeTeamFullName, homeTeamColor, homeTeamAlternateColor, homeTeamScore, homeTeamWinner, homeTeamRecord, awayTeamId, awayTeamMascot, awayTeamName, awayTeamAbbrev, awayTeamLogo, awayTeamLogoDark, awayTeamFullName, awayTeamColor, awayTeamAlternateColor, awayTeamScore, awayTeamWinner, awayTeamRecord ) } game_json <- jsonlite::fromJSON(jsonlite::toJSON(game_json), flatten = TRUE) plays <- game_json %>% purrr::pluck("plays") if ("coordinate.x" %in% names(plays) & "coordinate.y" %in% names(plays)) { plays <- plays %>% dplyr::mutate( # convert types coordinate.x = as.double(.data$coordinate.x), coordinate.y = as.double(.data$coordinate.y), # Free throws are adjusted automatically to 19' from baseline, which # corresponds to 13.75' from the center of the basket (originally # the center of the basket is (25, 0)) coordinate.y = dplyr::case_when( stringr::str_detect(.data$type.text, "Free Throw") ~ 13.75, TRUE ~ .data$coordinate.y ), coordinate.x = dplyr::case_when( stringr::str_detect(.data$type.text, "Free Throw") ~ 25, TRUE ~ .data$coordinate.x ), coordinate_x_transformed = dplyr::case_when( .data$team.id == homeTeamId ~ -1 * (.data$coordinate.y - 41.75), TRUE ~ .data$coordinate.y - 41.75 ), coordinate_y_transformed = dplyr::case_when( .data$team.id == homeTeamId ~ -1 * (.data$coordinate.x - 25), TRUE ~ .data$coordinate.x - 25 ) ) %>% dplyr::rename( "coordinate.x.raw" = "coordinate.x", "coordinate.y.raw" = "coordinate.y", "coordinate.x" = "coordinate_x_transformed", "coordinate.y" = "coordinate_y_transformed" ) } ## Written this way for compliance with data repository processing if ("participants" %in% names(plays)) { plays <- plays %>% tidyr::unnest_wider("participants") suppressWarnings( aths <- plays %>% dplyr::group_by(.data$id) %>% dplyr::select( "id", "athlete.id") %>% tidyr::unnest_wider("athlete.id", names_sep = "_") ) names(aths) <- c("play.id", "athlete.id.1", "athlete.id.2") plays <- plays %>% dplyr::bind_cols(aths) %>% janitor::clean_names() %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "athlete_id_1", "athlete_id_2", "athlete_id_3" )), ~as.integer(.x))) } ## Written this way for compliance with data repository processing if (!("homeTeamName" %in% names(plays))) { plays <- plays %>% dplyr::bind_cols(id_vars) } plays <- plays %>% dplyr::select(-dplyr::any_of(c("athlete.id", "athlete_id"))) %>% janitor::clean_names() %>% dplyr::mutate( game_id = gameId, season = season, season_type = season_type, game_date = game_date, game_date_time = game_date_time) %>% dplyr::rename(dplyr::any_of(c( "athlete_id_1" = "participants_0_athlete_id", "athlete_id_2" = "participants_1_athlete_id", "athlete_id_3" = "participants_2_athlete_id"))) plays <- plays %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "athlete_id_1", "athlete_id_2", "athlete_id_3", "type_id", "team_id" )), ~as.integer(.x))) plays_df <- plays %>% make_wehoop_data("ESPN WBB Play-by-Play Information from ESPN.com", Sys.time()) return(plays_df) } } #' **Parse ESPN WBB Team Box, helper function** #' @param resp Response object from the ESPN WBB game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wbb_team_box <- function(resp) { game_json <- resp %>% jsonlite::fromJSON() gameId <- as.integer(game_json[["header"]][["id"]]) game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) box_score_available <- game_json[["header"]][["competitions"]][["boxscoreAvailable"]] if (box_score_available == TRUE) { teams_box_score_df <- game_json[["boxscore"]][["teams"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) if (length(teams_box_score_df[["statistics"]][[1]]) > 0) { # Teams info columns and values teams_df <- game_json[["header"]][["competitions"]][["competitors"]][[1]] homeAway1 <- teams_df[["homeAway"]][1] homeAway1_team.id <- as.integer(teams_df[["id"]][1]) homeAway1_team.score <- as.integer(teams_df[["score"]][1]) homeAway1_team.winner <- teams_df[["winner"]][1] homeAway2 <- teams_df[["homeAway"]][2] homeAway2_team.id <- as.integer(teams_df[["id"]][2]) homeAway2_team.score <- as.integer(teams_df[["score"]][2]) homeAway2_team.winner <- teams_df[["winner"]][2] # Pivoting the table values for each team from long to wide statistics_df_1 <- teams_box_score_df[["statistics"]][[1]] %>% tibble::tibble() %>% dplyr::select("name", "displayValue") %>% tidyr::spread("name", "displayValue") statistics_df_2 <- teams_box_score_df[["statistics"]][[2]] %>% tibble::tibble() %>% dplyr::select("name", "displayValue") %>% tidyr::spread("name", "displayValue") # Assigning values to the correct data frame rows - 1 statistics_df_1$team.homeAway <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), homeAway1, homeAway2 ) statistics_df_1$team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), as.integer(homeAway1_team.score), as.integer(homeAway2_team.score) ) statistics_df_1$team.winner <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), homeAway1_team.winner, homeAway2_team.winner ) statistics_df_1$team.id <- as.integer(teams_box_score_df[["team.id"]][[1]]) statistics_df_1$team.uid <- teams_box_score_df[["team.uid"]][[1]] statistics_df_1$team.slug <- teams_box_score_df[["team.slug"]][[1]] statistics_df_1$team.location <- teams_box_score_df[["team.location"]][[1]] statistics_df_1$team.name <- teams_box_score_df[["team.name"]][[1]] statistics_df_1$team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[1]] statistics_df_1$team.displayName <- teams_box_score_df[["team.displayName"]][[1]] statistics_df_1$team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[1]] statistics_df_1$team.color <- teams_box_score_df[["team.color"]][[1]] statistics_df_1$team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[1]] statistics_df_1$team.logo <- teams_box_score_df[["team.logo"]][[1]] statistics_df_1$opponent.team.id <- as.integer(teams_box_score_df[["team.id"]][[2]]) statistics_df_1$opponent.team.uid <- teams_box_score_df[["team.uid"]][[2]] statistics_df_1$opponent.team.slug <- teams_box_score_df[["team.slug"]][[2]] statistics_df_1$opponent.team.location <- teams_box_score_df[["team.location"]][[2]] statistics_df_1$opponent.team.name <- teams_box_score_df[["team.name"]][[2]] statistics_df_1$opponent.team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[2]] statistics_df_1$opponent.team.displayName <- teams_box_score_df[["team.displayName"]][[2]] statistics_df_1$opponent.team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[2]] statistics_df_1$opponent.team.color <- teams_box_score_df[["team.color"]][[2]] statistics_df_1$opponent.team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[2]] statistics_df_1$opponent.team.logo <- teams_box_score_df[["team.logo"]][[2]] statistics_df_1$opponent.team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), as.integer(homeAway2_team.score), as.integer(homeAway1_team.score) ) # Assigning values to the correct data frame rows - 2 statistics_df_2$team.homeAway <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), homeAway2, homeAway1 ) statistics_df_2$team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), as.integer(homeAway2_team.score), as.integer(homeAway1_team.score) ) statistics_df_2$team.winner <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), homeAway2_team.winner, homeAway1_team.winner ) statistics_df_2$team.id <- as.integer(teams_box_score_df[["team.id"]][[2]]) statistics_df_2$team.uid <- teams_box_score_df[["team.uid"]][[2]] statistics_df_2$team.slug <- teams_box_score_df[["team.slug"]][[2]] statistics_df_2$team.location <- teams_box_score_df[["team.location"]][[2]] statistics_df_2$team.name <- teams_box_score_df[["team.name"]][[2]] statistics_df_2$team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[2]] statistics_df_2$team.displayName <- teams_box_score_df[["team.displayName"]][[2]] statistics_df_2$team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[2]] statistics_df_2$team.color <- teams_box_score_df[["team.color"]][[2]] statistics_df_2$team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[2]] statistics_df_2$team.logo <- teams_box_score_df[["team.logo"]][[2]] statistics_df_2$opponent.team.id <- as.integer(teams_box_score_df[["team.id"]][[1]]) statistics_df_2$opponent.team.uid <- teams_box_score_df[["team.uid"]][[1]] statistics_df_2$opponent.team.slug <- teams_box_score_df[["team.slug"]][[1]] statistics_df_2$opponent.team.location <- teams_box_score_df[["team.location"]][[1]] statistics_df_2$opponent.team.name <- teams_box_score_df[["team.name"]][[1]] statistics_df_2$opponent.team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[1]] statistics_df_2$opponent.team.displayName <- teams_box_score_df[["team.displayName"]][[1]] statistics_df_2$opponent.team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[1]] statistics_df_2$opponent.team.color <- teams_box_score_df[["team.color"]][[1]] statistics_df_2$opponent.team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[1]] statistics_df_2$opponent.team.logo <- teams_box_score_df[["team.logo"]][[1]] statistics_df_2$opponent.team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), as.integer(homeAway1_team.score), as.integer(homeAway2_team.score) ) complete_statistics_df <- statistics_df_1 %>% dplyr::bind_rows(statistics_df_2) # Assigning game/season level data to team box score and converting types complete_statistics_df$season <- game_json[["header"]][["season"]][["year"]] complete_statistics_df$season_type <- game_json[["header"]][["season"]][["type"]] complete_statistics_df$game_date <- game_date complete_statistics_df$game_date_time <- game_date_time complete_statistics_df$game_id <- as.integer(gameId) suppressWarnings( complete_statistics_df <- complete_statistics_df %>% tidyr::separate("fieldGoalsMade-fieldGoalsAttempted", into = c("fieldGoalsMade", "fieldGoalsAttempted"), sep = "-") %>% tidyr::separate("freeThrowsMade-freeThrowsAttempted", into = c("freeThrowsMade", "freeThrowsAttempted"), sep = "-") %>% tidyr::separate("threePointFieldGoalsMade-threePointFieldGoalsAttempted", into = c("threePointFieldGoalsMade", "threePointFieldGoalsAttempted"), sep = "-") %>% dplyr::mutate(dplyr::across(c( "fieldGoalPct", "freeThrowPct", "threePointFieldGoalPct" ), ~as.numeric(.x))) %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "assists", "blocks", "defensiveRebounds", "fieldGoalsMade", "fieldGoalsAttempted", "flagrantFouls", "fouls", "freeThrowsMade", "freeThrowsAttempted", "offensiveRebounds", "steals", "teamTurnovers", "technicalFouls", "threePointFieldGoalsMade", "threePointFieldGoalsAttempted", "totalRebounds", "totalTechnicalFouls", "totalTurnovers", "turnovers" )), ~as.integer(.x))) ) team_box_score <- complete_statistics_df %>% janitor::clean_names() %>% dplyr::select(dplyr::any_of(c( "game_id", "season", "season_type", "game_date", "game_date_time", "team_id", "team_uid", "team_slug", "team_location", "team_name", "team_abbreviation", "team_display_name", "team_short_display_name", "team_color", "team_alternate_color", "team_logo", "team_home_away", "team_score", "team_winner")), tidyr::everything()) %>% make_wehoop_data("ESPN WBB Team Box Information from ESPN.com", Sys.time()) return(team_box_score) } } } #' **Parse ESPN WBB Player Box, helper function** #' @param resp Response object from the ESPN WBB game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wbb_player_box <- function(resp){ game_json <- resp %>% jsonlite::fromJSON(flatten = TRUE) players_box_score_df <- game_json[["boxscore"]][["players"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% as.data.frame() gameId <- as.integer(game_json[["header"]][["id"]]) season <- game_json[["header"]][["season"]][["year"]] season_type <- game_json[["header"]][["season"]][["type"]] game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) boxScoreAvailable <- game_json[["header"]][["competitions"]][["boxscoreAvailable"]] boxScoreSource <- game_json[["header"]][["competitions"]][["boxscoreSource"]] valid_stats <- players_box_score_df %>% tidyr::unnest("statistics") valid_athletes <- is.data.frame(valid_stats[["athletes"]][[1]]) && is.data.frame(valid_stats[["athletes"]][[2]]) # This is checking if [[athletes]][[1]]'s stat rebounds is able to be converted to a numeric value # without introducing NA's suppressWarnings( valid_stats <- players_box_score_df[["statistics"]][[1]][["athletes"]][[1]][["stats"]][[1]] %>% purrr::pluck(7) %>% as.numeric() ) if (boxScoreAvailable == TRUE && length(players_box_score_df[["statistics"]][[1]][["athletes"]][[1]]) > 1 && length(players_box_score_df[["statistics"]][[1]][["athletes"]][[1]][["stats"]][[1]]) > 1 && valid_athletes && !is.na(valid_stats)) { players_df <- players_box_score_df %>% tidyr::unnest("statistics") %>% tidyr::unnest("athletes") if (length(players_box_score_df[["statistics"]]) > 1 && length(players_df$stats[[1]] > 0)) { players_df <- jsonlite::fromJSON(jsonlite::toJSON(game_json[["boxscore"]][["players"]]), flatten = TRUE) %>% tidyr::unnest("statistics") %>% tidyr::unnest("athletes") stat_cols <- players_df$keys[[1]] stats <- players_df$stats stats_df <- as.data.frame(do.call(rbind,stats)) colnames(stats_df) <- stat_cols suppressWarnings( stats_df <- stats_df %>% tidyr::separate("fieldGoalsMade-fieldGoalsAttempted", into = c("fieldGoalsMade", "fieldGoalsAttempted"), sep = "-") %>% tidyr::separate("freeThrowsMade-freeThrowsAttempted", into = c("freeThrowsMade", "freeThrowsAttempted"), sep = "-") %>% tidyr::separate("threePointFieldGoalsMade-threePointFieldGoalsAttempted", into = c("threePointFieldGoalsMade", "threePointFieldGoalsAttempted"), sep = "-") %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "minutes", "fieldGoalPct", "freeThrowPct", "threePointFieldGoalPct" )), ~as.numeric(.x))) %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "assists", "blocks", "defensiveRebounds", "fieldGoalsMade", "fieldGoalsAttempted", "flagrantFouls", "fouls", "freeThrowsMade", "freeThrowsAttempted", "offensiveRebounds", "steals", "teamTurnovers", "technicalFouls", "threePointFieldGoalsMade", "threePointFieldGoalsAttempted", "rebounds", "totalTechnicalFouls", "totalTurnovers", "turnovers", "points" )), ~as.integer(.x))) ) players_df_did_not_play <- players_df %>% dplyr::filter(.data$didNotPlay) %>% dplyr::select(dplyr::any_of(c( "starter", "ejected", "didNotPlay", "reason", "active", "athlete.displayName", "athlete.jersey", "athlete.id", "athlete.shortName", "athlete.headshot.href", "athlete.position.name", "athlete.position.abbreviation", "team.displayName", "team.shortDisplayName", "team.location", "team.name", "team.logo", "team.id", "team.uid", "team.slug", "team.abbreviation", "team.color", "team.alternateColor" ))) players_df <- players_df %>% dplyr::filter(!.data$didNotPlay) %>% dplyr::select(dplyr::any_of(c( "starter", "ejected", "didNotPlay", "reason", "active", "athlete.displayName", "athlete.jersey", "athlete.id", "athlete.shortName", "athlete.headshot.href", "athlete.position.name", "athlete.position.abbreviation", "team.displayName", "team.shortDisplayName", "team.location", "team.name", "team.logo", "team.id", "team.uid", "team.slug", "team.abbreviation", "team.color", "team.alternateColor" ))) players_df <- stats_df %>% dplyr::bind_cols(players_df) %>% dplyr::bind_rows(players_df_did_not_play) players_df <- players_df %>% dplyr::select(dplyr::any_of(c( "athlete.displayName", "team.shortDisplayName")), tidyr::everything()) %>% janitor::clean_names() %>% dplyr::mutate( game_id = gameId, season = season, season_type = season_type, game_date = game_date, game_date_time = game_date_time) teams_df <- game_json[["header"]][["competitions"]][["competitors"]][[1]] homeAway1 <- teams_df[["homeAway"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.id <- as.integer(teams_df[["id"]] %>% purrr::pluck(1, .default = NA_integer_)) homeAway1_team.location <- teams_df[["team.location"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.name <- teams_df[["team.name"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.abbreviation <- teams_df[["team.abbreviation"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.displayName <- teams_df[["team.displayName"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.logos <- teams_df[["team.logos"]][[1]][["href"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.color <- teams_df[["team.color"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.alternateColor <- teams_df[["team.alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.winner <- teams_df[["winner"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.score <- as.integer(teams_df[["score"]] %>% purrr::pluck(1, .default = NA_integer_)) homeAway2 <- teams_df[["homeAway"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.id <- as.integer(teams_df[["id"]] %>% purrr::pluck(2, .default = NA_integer_)) homeAway2_team.location <- teams_df[["team.location"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.name <- teams_df[["team.name"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.abbreviation <- teams_df[["team.abbreviation"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.displayName <- teams_df[["team.displayName"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.logos <- teams_df[["team.logos"]][[2]][["href"]] %>% purrr::pluck(1, .default = NA_character_) homeAway2_team.color <- teams_df[["team.color"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.alternateColor <- teams_df[["team.alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.winner <- teams_df[["winner"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.score <- as.integer(teams_df[["score"]] %>% purrr::pluck(2, .default = NA_integer_)) players_df <- players_df %>% dplyr::mutate( home_away = ifelse(.data$team_id == homeAway1_team.id, homeAway1, homeAway2), team_winner = ifelse(.data$team_id == homeAway1_team.id, homeAway1_team.winner, homeAway2_team.winner), team_score = ifelse(.data$team_id == homeAway1_team.id, homeAway1_team.score, homeAway2_team.score), opponent_team_id = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.id, homeAway1_team.id), opponent_team_name = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.name, homeAway1_team.name), opponent_team_location = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.location, homeAway1_team.location), opponent_team_display_name = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.displayName, homeAway1_team.displayName), opponent_team_abbreviation = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.abbreviation, homeAway1_team.abbreviation), opponent_team_logo = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.logos, homeAway1_team.logos), opponent_team_color = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.color, homeAway1_team.color), opponent_team_alternate_color = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.alternateColor, homeAway1_team.alternateColor), opponent_team_score = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.score, homeAway1_team.score), ) %>% dplyr::arrange(.data$home_away) player_box_score <- players_df %>% dplyr::select(dplyr::any_of(c( "game_id", "season", "season_type", "game_date", "game_date_time", "athlete_id", "athlete_display_name", "team_id", "team_name", "team_location", "team_short_display_name", "minutes", "field_goals_made", "field_goals_attempted", "three_point_field_goals_made", "three_point_field_goals_attempted", "free_throws_made", "free_throws_attempted", "offensive_rebounds", "defensive_rebounds", "rebounds", "assists", "steals", "blocks", "turnovers", "fouls", "points", "starter", "ejected", "did_not_play", "reason", "active", "athlete_jersey", "athlete_short_name", "athlete_headshot_href", "athlete_position_name", "athlete_position_abbreviation", "team_display_name", "team_uid", "team_slug", "team_logo", "team_abbreviation", "team_color", "team_alternate_color", "home_away", "team_winner", "team_score", "opponent_team_id", "opponent_team_name", "opponent_team_location", "opponent_team_display_name", "opponent_team_abbreviation", "opponent_team_logo", "opponent_team_color", "opponent_team_alternate_color", "opponent_team_score" ))) %>% dplyr::mutate_at(c( "athlete_id", "team_id", "team_score", "opponent_team_score" ), as.integer) %>% make_wehoop_data("ESPN WBB Player Box Information from ESPN.com", Sys.time()) return(player_box_score) } } }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/espn_wbb_data.R
#' Get ESPN's WNBA game data (play-by-play, team and player box) #' @author Saiem Gilani #' @param game_id Game ID #' @return A named list of dataframes: Plays, Team, Player #' #' **Plays** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |id |character | #' |sequence_number |character | #' |text |character | #' |away_score |integer | #' |home_score |integer | #' |scoring_play |logical | #' |score_value |integer | #' |wallclock |character | #' |shooting_play |logical | #' |type_id |integer | #' |type_text |character | #' |period_number |integer | #' |period_display_value |character | #' |clock_display_value |character | #' |team_id |integer | #' |coordinate_x_raw |numeric | #' |coordinate_y_raw |numeric | #' |coordinate_x |numeric | #' |coordinate_y |numeric | #' |play_id |character | #' |athlete_id_1 |integer | #' |athlete_id_2 |integer | #' |athlete_id_3 |integer | #' |home_team_id |integer | #' |home_team_mascot |character | #' |home_team_name |character | #' |home_team_abbrev |character | #' |home_team_logo |character | #' |home_team_logo_dark |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_team_alternate_color |character | #' |home_team_score |integer | #' |home_team_winner |logical | #' |home_team_record |character | #' |away_team_id |integer | #' |away_team_mascot |character | #' |away_team_name |character | #' |away_team_abbrev |character | #' |away_team_logo |character | #' |away_team_logo_dark |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_team_alternate_color |character | #' |away_team_score |integer | #' |away_team_winner |logical | #' |away_team_record |character | #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' #' **Team** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |team_id |integer | #' |team_uid |character | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_logo |character | #' |team_home_away |character | #' |team_score |integer | #' |team_winner |logical | #' |assists |integer | #' |blocks |integer | #' |defensive_rebounds |integer | #' |field_goal_pct |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |flagrant_fouls |integer | #' |fouls |integer | #' |free_throw_pct |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |largest_lead |character | #' |offensive_rebounds |integer | #' |steals |integer | #' |team_turnovers |integer | #' |technical_fouls |integer | #' |three_point_field_goal_pct |numeric | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |total_rebounds |integer | #' |total_technical_fouls |integer | #' |total_turnovers |integer | #' |turnovers |integer | #' |opponent_team_id |integer | #' |opponent_team_uid |character | #' |opponent_team_slug |character | #' |opponent_team_location |character | #' |opponent_team_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_display_name |character | #' |opponent_team_short_display_name |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_logo |character | #' |opponent_team_score |integer | #' #' **Player** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |athlete_id |integer | #' |athlete_display_name |character | #' |team_id |integer | #' |team_name |character | #' |team_location |character | #' |team_short_display_name |character | #' |minutes |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |offensive_rebounds |integer | #' |defensive_rebounds |integer | #' |rebounds |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls |integer | #' |plus_minus |character | #' |points |integer | #' |starter |logical | #' |ejected |logical | #' |did_not_play |logical | #' |reason |character | #' |active |logical | #' |athlete_jersey |character | #' |athlete_short_name |character | #' |athlete_headshot_href |character | #' |athlete_position_name |character | #' |athlete_position_abbreviation |character | #' |team_display_name |character | #' |team_uid |character | #' |team_slug |character | #' |team_logo |character | #' |team_abbreviation |character | #' |team_color |character | #' |team_alternate_color |character | #' |home_away |character | #' |team_winner |logical | #' |team_score |integer | #' |opponent_team_id |integer | #' |opponent_team_name |character | #' |opponent_team_location |character | #' |opponent_team_display_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_logo |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WNBA Game #' @family ESPN WNBA Functions #' @examples #' \donttest{ #' try(espn_wnba_game_all(game_id = 401244185)) #' } espn_wnba_game_all <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") #---- Play-by-Play ------ tryCatch( expr = { plays_df <- helper_espn_wnba_pbp(resp) if (is.null(plays_df)) { message(glue::glue("{Sys.time()}: No play-by-play data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) #---- Team Box ------ tryCatch( expr = { team_box_score <- helper_espn_wnba_team_box(resp) if (is.null(team_box_score)) { message(glue::glue("{Sys.time()}: No team box score data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no team box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) #---- Player Box ------ tryCatch( expr = { player_box_score <- helper_espn_wnba_player_box(resp) if (is.null(player_box_score)) { message(glue::glue("{Sys.time()}: No player box score data for {game_id} available!")) } }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no player box score data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) pbp <- c(list(plays_df), list(team_box_score), list(player_box_score)) names(pbp) <- c("Plays", "Team", "Player") return(pbp) } #' Get ESPN's WNBA play by play data #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a play-by-play data frame #' #' **Plays** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |id |character | #' |sequence_number |character | #' |text |character | #' |away_score |integer | #' |home_score |integer | #' |scoring_play |logical | #' |score_value |integer | #' |wallclock |character | #' |shooting_play |logical | #' |type_id |integer | #' |type_text |character | #' |period_number |integer | #' |period_display_value |character | #' |clock_display_value |character | #' |team_id |integer | #' |coordinate_x_raw |numeric | #' |coordinate_y_raw |numeric | #' |coordinate_x |numeric | #' |coordinate_y |numeric | #' |play_id |character | #' |athlete_id_1 |integer | #' |athlete_id_2 |integer | #' |athlete_id_3 |integer | #' |home_team_id |integer | #' |home_team_mascot |character | #' |home_team_name |character | #' |home_team_abbrev |character | #' |home_team_logo |character | #' |home_team_logo_dark |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_team_alternate_color |character | #' |home_team_score |integer | #' |home_team_winner |logical | #' |home_team_record |character | #' |away_team_id |integer | #' |away_team_mascot |character | #' |away_team_name |character | #' |away_team_abbrev |character | #' |away_team_logo |character | #' |away_team_logo_dark |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_team_alternate_color |character | #' |away_team_score |integer | #' |away_team_winner |logical | #' |away_team_record |character | #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WNBA PBP #' @family ESPN WNBA Functions #' @examples #' #' \donttest{ #' try(espn_wnba_pbp(game_id = 401455681)) #' } espn_wnba_pbp <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") #---- Play-by-Play ------ tryCatch( expr = { plays_df <- helper_espn_wnba_pbp(resp) if (is.null(plays_df)) { return(message(glue::glue("{Sys.time()}: No play-by-play data for {game_id} available!"))) } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(plays_df) } #' Get ESPN's WNBA team box data #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a team boxscore data frame #' #' **Team** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |team_id |integer | #' |team_uid |character | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_logo |character | #' |team_home_away |character | #' |team_score |integer | #' |team_winner |logical | #' |assists |integer | #' |blocks |integer | #' |defensive_rebounds |integer | #' |field_goal_pct |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |flagrant_fouls |integer | #' |fouls |integer | #' |free_throw_pct |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |largest_lead |character | #' |offensive_rebounds |integer | #' |steals |integer | #' |team_turnovers |integer | #' |technical_fouls |integer | #' |three_point_field_goal_pct |numeric | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |total_rebounds |integer | #' |total_technical_fouls |integer | #' |total_turnovers |integer | #' |turnovers |integer | #' |opponent_team_id |integer | #' |opponent_team_uid |character | #' |opponent_team_slug |character | #' |opponent_team_location |character | #' |opponent_team_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_display_name |character | #' |opponent_team_short_display_name |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_logo |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WNBA Team Box #' @family ESPN WNBA Functions #' @examples #' #' \donttest{ #' try(espn_wnba_team_box(game_id = 401244185)) #' } espn_wnba_team_box <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") #---- Team Box ------ tryCatch( expr = { team_box_score <- helper_espn_wnba_team_box(resp) if (is.null(team_box_score)) { return(message(glue::glue("{Sys.time()}: No team box score data for {game_id} available!"))) } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team box score data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(team_box_score) } #' Get ESPN's WNBA player box data #' @author Saiem Gilani #' @param game_id Game ID #' @return Returns a player boxscore data frame #' #' **Player** #' #' #' |col_name |types | #' |:---------------------------------|:---------| #' |game_id |integer | #' |season |integer | #' |season_type |integer | #' |game_date |Date | #' |game_date_time |POSIXct | #' |athlete_id |integer | #' |athlete_display_name |character | #' |team_id |integer | #' |team_name |character | #' |team_location |character | #' |team_short_display_name |character | #' |minutes |numeric | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |three_point_field_goals_made |integer | #' |three_point_field_goals_attempted |integer | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |offensive_rebounds |integer | #' |defensive_rebounds |integer | #' |rebounds |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls |integer | #' |plus_minus |character | #' |points |integer | #' |starter |logical | #' |ejected |logical | #' |did_not_play |logical | #' |reason |character | #' |active |logical | #' |athlete_jersey |character | #' |athlete_short_name |character | #' |athlete_headshot_href |character | #' |athlete_position_name |character | #' |athlete_position_abbreviation |character | #' |team_display_name |character | #' |team_uid |character | #' |team_slug |character | #' |team_logo |character | #' |team_abbreviation |character | #' |team_color |character | #' |team_alternate_color |character | #' |home_away |character | #' |team_winner |logical | #' |team_score |integer | #' |opponent_team_id |integer | #' |opponent_team_name |character | #' |opponent_team_location |character | #' |opponent_team_display_name |character | #' |opponent_team_abbreviation |character | #' |opponent_team_logo |character | #' |opponent_team_color |character | #' |opponent_team_alternate_color |character | #' |opponent_team_score |integer | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WNBA Player Box #' @family ESPN WNBA Functions #' @examples #' \donttest{ #' try(espn_wnba_player_box(game_id = 401244185)) #' } #' espn_wnba_player_box <- function(game_id){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) summary_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/summary?" ## Inputs ## game_id full_url <- paste0(summary_url, "event=", game_id) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") #---- Player Box ------ tryCatch( expr = { player_box_score <- helper_espn_wnba_player_box(resp) if (is.null(player_box_score)) { return(message(glue::glue("{Sys.time()}: No player box score data for {game_id} available!"))) } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player box score data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(player_box_score) } #' **Get ESPN WNBA game rosters** #' @author Saiem Gilani #' @param game_id Game ID #' @return A game rosters data frame #' #' |col_name |types | #' |:-----------------------|:---------| #' |athlete_id |integer | #' |athlete_uid |character | #' |athlete_guid |character | #' |athlete_type |character | #' |sdr |integer | #' |first_name |character | #' |last_name |character | #' |full_name |character | #' |athlete_display_name |character | #' |short_name |character | #' |weight |numeric | #' |display_weight |character | #' |height |numeric | #' |display_height |character | #' |age |integer | #' |date_of_birth |character | #' |slug |character | #' |headshot_href |character | #' |headshot_alt |character | #' |jersey |character | #' |position_id |integer | #' |position_name |character | #' |position_display_name |character | #' |position_abbreviation |character | #' |position_leaf |logical | #' |linked |logical | #' |years |integer | #' |active |logical | #' |status_id |integer | #' |status_name |character | #' |status_type |character | #' |status_abbreviation |character | #' |birth_place_city |character | #' |birth_place_state |character | #' |birth_place_country |character | #' |starter |logical | #' |valid |logical | #' |did_not_play |logical | #' |display_name |character | #' |reason |character | #' |ejected |logical | #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_is_active |logical | #' |is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' |logos_href_2 |character | #' |logos_href_3 |character | #' |game_id |integer | #' |order |integer | #' |home_away |character | #' |winner |logical | #' |draft_display_text |character | #' |draft_round |integer | #' |draft_year |integer | #' |draft_selection |integer | #' |hand_type |character | #' |hand_abbreviation |character | #' |hand_display_value |character | #' |citizenship |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @import rvest #' @export #' @keywords WNBA Game Roster #' @family ESPN WNBA Functions #' #' @examples #' \donttest{ #' try(espn_wnba_game_rosters(game_id = 401244185)) #' } espn_wnba_game_rosters <- function(game_id) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) tryCatch( expr = { play_base_url <- paste0( "https://sports.core.api.espn.com/v2/sports/basketball/leagues/wnba/events/", game_id, "/competitions/", game_id,"/competitors/") game_res <- httr::RETRY("GET", play_base_url) # Check the result check_status(game_res) game_resp <- game_res %>% httr::content(as = "text", encoding = "UTF-8") game_df <- jsonlite::fromJSON(game_resp)[["items"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% dplyr::rename("team_statistics_href" = "statistics.$ref") colnames(game_df) <- gsub(".\\$ref","_href", colnames(game_df)) game_df <- game_df %>% dplyr::rename( "team_id" = "id", "team_uid" = "uid") game_df$game_id <- game_id teams_df <- purrr::map_dfr(game_df$team_href, function(x){ res <- httr::RETRY("GET", x) # Check the result check_status(res) team_df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["againstTheSpreadRecords"]] <- NULL team_df[["oddsRecords"]] <- NULL team_df[["college"]] <- NULL team_df[["transactions"]] <- NULL team_df[["leaders"]] <- NULL team_df[["depthCharts"]] <- NULL team_df[["awards"]] <- NULL team_df[["events"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list, as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.rel..scoreboard.", "logos.rel..scoreboard..1", "logos.rel..scoreboard.2", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.rel..dark..1", "logos.lastUpdated.1", "logos.width.2", "logos.height.2", "logos.alt.2", "logos.rel..full..2", "logos.rel..scoreboard.", "logos.lastUpdated.2", "logos.width.3", "logos.height.3", "logos.alt.3", "logos.rel..full..3", "logos.lastUpdated.3", "X.ref", "X.ref.1", "X.ref.2"))) %>% janitor::clean_names() colnames(team_df)[1:13] <- paste0("team_", colnames(team_df)[1:13]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") %>% dplyr::left_join( game_df %>% dplyr::select( "game_id", "team_id", "team_uid", "order", "homeAway", "winner", "roster_href"), by = c("team_id" = "team_id", "team_uid" = "team_uid") ) }) ## Inputs ## game_id team_roster_df <- purrr::map_dfr(teams_df$team_id, function(x){ res <- httr::RETRY("GET", paste0(play_base_url, x, "/roster")) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_play_df <- jsonlite::fromJSON(resp)[["entries"]] raw_play_df <- raw_play_df %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% dplyr::mutate(team_id = x) %>% dplyr::select(-"period", -"forPlayerId", -"active") raw_play_df <- raw_play_df %>% dplyr::left_join(teams_df, by = c("team_id" = "team_id")) }) colnames(team_roster_df) <- gsub(".\\$ref","_href", colnames(team_roster_df)) athlete_roster_df <- purrr::map_dfr(team_roster_df$athlete_href, function(x){ res <- httr::RETRY("GET", x) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_play_df <- jsonlite::fromJSON(resp, flatten = TRUE) raw_play_df[["links"]] <- NULL raw_play_df[["injuries"]] <- NULL raw_play_df[["teams"]] <- NULL raw_play_df[["team"]] <- NULL raw_play_df[["college"]] <- NULL raw_play_df[["proAthlete"]] <- NULL raw_play_df[["statistics"]] <- NULL raw_play_df[["notes"]] <- NULL raw_play_df[["eventLog"]] <- NULL raw_play_df[["$ref"]] <- NULL raw_play_df[["position"]][["$ref"]] <- NULL birth_place <- raw_play_df %>% purrr::pluck("birthPlace") %>% as.data.frame() raw_play_df[["birthPlace"]] <- NULL raw_play_df2 <- raw_play_df %>% as.data.frame() %>% dplyr::bind_cols(birth_place) %>% dplyr::mutate(id = as.integer(.data$id)) %>% dplyr::rename( "athlete_id" = "id", "athlete_uid" = "uid", "athlete_guid" = "guid", "athlete_type" = "type", "athlete_display_name" = "displayName" ) raw_play_df2 <- raw_play_df2 %>% dplyr::left_join(team_roster_df, by = c("athlete_id" = "playerId")) }) colnames(athlete_roster_df) <- gsub(".\\$ref","_href", colnames(athlete_roster_df)) athlete_roster_df <- athlete_roster_df %>% janitor::clean_names() %>% dplyr::rename( "birth_place_city" = "city", "birth_place_state" = "state", "birth_place_country" = "country") %>% dplyr::select(-dplyr::any_of(c( "x_ref", "x_ref_1", "contract_ref", "contract_ref_1", "contract_ref_2", "draft_ref", "draft_ref_1", "athlete_href", "position_ref", "position_href", "roster_href", "statistics_href"))) %>% dplyr::mutate_at(c( "game_id", "athlete_id", "team_id", "position_id", "status_id", "sdr", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WNBA Game Roster Information from ESPN.com",Sys.time()) }, error = function(e) { message( glue::glue( "{Sys.time()}: Invalid arguments or no game roster data for {game_id} available!" ) ) }, warning = function(w) { }, finally = { } ) return(athlete_roster_df) } #' Get ESPN's WNBA team names and ids #' @author Saiem Gilani #' @return Returns a tibble #' #' |col_name |types | #' |:---------------|:---------| #' |team_id |integer | #' |team |character | #' |mascot |character | #' |display_name |character | #' |short_name |character | #' |abbreviation |character | #' |color |character | #' |alternate_color |character | #' |logo |character | #' |logo_dark |character | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows row_number group_by mutate as_tibble ungroup #' @importFrom tidyr unnest unnest_wider everything pivot_wider #' @import rvest #' @export #' @keywords WNBA Teams #' @family ESPN WNBA Functions #' @examples #' \donttest{ #' try(espn_wnba_teams()) #' } espn_wnba_teams <- function(){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) play_base_url <- "http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/teams?limit=1000" res <- httr::RETRY( "GET", play_base_url ) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") ## Inputs ## game_id leagues <- jsonlite::fromJSON(resp)[["sports"]][["leagues"]][[1]][['teams']][[1]][['team']] %>% dplyr::group_by(.data$id) %>% tidyr::unnest_wider("logos", names_sep = "_") %>% tidyr::unnest_wider("logos_href", names_sep = "_") %>% dplyr::select( -"logos_width", -"logos_height", -"logos_alt", -"logos_rel") %>% dplyr::ungroup() wnba_teams <- leagues %>% dplyr::select( "id", "location", "name", "displayName", "shortDisplayName", "abbreviation", "color", "alternateColor", "logos_href_1", "logos_href_2") %>% dplyr::rename( "logo" = "logos_href_1", "logo_dark" = "logos_href_2", "mascot" = "name", "team" = "location", "team_id" = "id", "alternate_color" = "alternateColor", "short_name" = "shortDisplayName", "display_name" = "displayName") %>% dplyr::mutate(team_id = as.integer(.data$team_id)) %>% make_wehoop_data("ESPN WNBA Teams Information from ESPN.com",Sys.time()) return(wnba_teams) } #' **Get WNBA schedule for a specific year/date from ESPN's API** #' #' @param season Either numeric or character #' @author Saiem Gilani. #' @return Returns a tibble #' #' |col_name |types | #' |:-------------------|:---------| #' |matchup |character | #' |matchup_short |character | #' |season |integer | #' |season_type |integer | #' |season_slug |character | #' |game_id |integer | #' |game_uid |character | #' |game_date |Date | #' |attendance |integer | #' |status_name |character | #' |broadcast_market |character | #' |broadcast_name |character | #' |start_date |character | #' |game_date_time |POSIXct | #' |home_team_name |character | #' |home_team_logo |character | #' |home_team_abb |character | #' |home_team_id |integer | #' |home_team_location |character | #' |home_team_full_name |character | #' |home_team_color |character | #' |home_score |integer | #' |home_win |integer | #' |home_record |character | #' |away_team_name |character | #' |away_team_logo |character | #' |away_team_abb |character | #' |away_team_id |integer | #' |away_team_location |character | #' |away_team_full_name |character | #' |away_team_color |character | #' |away_score |integer | #' |away_win |integer | #' |away_record |character | #' #' @import utils #' @import rvest #' @importFrom dplyr select rename any_of mutate #' @importFrom jsonlite fromJSON #' @importFrom tidyr unnest_wider unchop hoist #' @importFrom glue glue #' @importFrom lubridate with_tz ymd_hm #' @import rvest #' @export #' @keywords WNBA Scoreboard #' @family ESPN WNBA Functions #' @examples #' # Get schedule from date 2022-08-31 #' \donttest{ #' try(espn_wnba_scoreboard (season = "20220831")) #' } espn_wnba_scoreboard <- function(season){ # message(glue::glue("Returning data for {season}!")) max_year <- substr(Sys.Date(), 1,4) if (!(as.integer(substr(season, 1, 4)) %in% c(2001:max_year))) { message(paste("Error: Season must be between 2001 and", max_year)) } # year > 2000 season <- as.character(season) season_dates <- season schedule_api <- paste0("http://site.api.espn.com/apis/site/v2/sports/basketball/wnba/scoreboard?limit=1000&dates=", season_dates) res <- httr::RETRY( "GET", schedule_api ) # Check the result check_status(res) tryCatch( expr = { raw_sched <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) wnba_data <- raw_sched[["events"]] %>% tibble::tibble(data = .data$.) %>% tidyr::unnest_wider("data") %>% tidyr::unchop("competitions") %>% dplyr::select( -"id", -"uid", -"date", -"status") %>% tidyr::unnest_wider("competitions") %>% dplyr::rename( "matchup" = "name", "matchup_short" = "shortName", "game_id" = "id", "game_uid" = "uid", "game_date" = "date" ) %>% tidyr::hoist("status", status_name = list("type", "name")) %>% dplyr::select(!dplyr::any_of( c( "timeValid", "neutralSite", "conferenceCompetition", "recent", "venue", "type" ) )) %>% tidyr::unnest_wider("season", names_sep = "_") %>% dplyr::rename("season" = "season_year") %>% dplyr::select(-dplyr::any_of("status")) wnba_data <- wnba_data %>% dplyr::mutate( game_date_time = lubridate::ymd_hm(substr(.data$game_date, 1, nchar(.data$game_date) - 1)) %>% lubridate::with_tz(tzone = "America/New_York"), game_date = as.Date(substr(.data$game_date_time, 1, 10))) wnba_data <- wnba_data %>% tidyr::hoist( "competitors", homeAway = list(1,"homeAway") ) wnba_data <- wnba_data %>% tidyr::hoist( "competitors", team1_team_name = list(1, "team", "name"), team1_team_logo = list(1, "team", "logo"), team1_team_abb = list(1, "team", "abbreviation"), team1_team_id = list(1, "team", "id"), team1_team_location = list(1, "team", "location"), team1_team_full = list(1, "team", "displayName"), team1_team_color = list(1, "team", "color"), team1_score = list(1, "score"), team1_win = list(1, "winner"), team1_record = list(1, "records", 1, "summary"), # away team team2_team_name = list(2, "team", "name"), team2_team_logo = list(2, "team", "logo"), team2_team_abb = list(2, "team", "abbreviation"), team2_team_id = list(2, "team", "id"), team2_team_location = list(2, "team", "location"), team2_team_full = list(2, "team", "displayName"), team2_team_color = list(2, "team", "color"), team2_score = list(2, "score"), team2_win = list(2, "winner"), team2_record = list(2, "records", 1, "summary")) wnba_data <- wnba_data %>% dplyr::mutate( home_team_name = ifelse(.data$homeAway == "home",.data$team1_team_name, .data$team2_team_name), home_team_logo = ifelse(.data$homeAway == "home",.data$team1_team_logo, .data$team2_team_logo), home_team_abb = ifelse(.data$homeAway == "home",.data$team1_team_abb, .data$team2_team_abb), home_team_id = ifelse(.data$homeAway == "home",.data$team1_team_id, .data$team2_team_id), home_team_location = ifelse(.data$homeAway == "home",.data$team1_team_location, .data$team2_team_location), home_team_full_name = ifelse(.data$homeAway == "home",.data$team1_team_full, .data$team2_team_full), home_team_color = ifelse(.data$homeAway == "home",.data$team1_team_color, .data$team2_team_color), home_score = ifelse(.data$homeAway == "home",.data$team1_score, .data$team2_score), home_win = ifelse(.data$homeAway == "home",.data$team1_win, .data$team2_win), home_record = ifelse(.data$homeAway == "home",.data$team1_record, .data$team2_record), away_team_name = ifelse(.data$homeAway == "away",.data$team1_team_name, .data$team2_team_name), away_team_logo = ifelse(.data$homeAway == "away",.data$team1_team_logo, .data$team2_team_logo), away_team_abb = ifelse(.data$homeAway == "away",.data$team1_team_abb, .data$team2_team_abb), away_team_id = ifelse(.data$homeAway == "away",.data$team1_team_id, .data$team2_team_id), away_team_location = ifelse(.data$homeAway == "away",.data$team1_team_location, .data$team2_team_location), away_team_full_name = ifelse(.data$homeAway == "away",.data$team1_team_full, .data$team2_team_full), away_team_color = ifelse(.data$homeAway == "away",.data$team1_team_color, .data$team2_team_color), away_score = ifelse(.data$homeAway == "away",.data$team1_score, .data$team2_score), away_win = ifelse(.data$homeAway == "away",.data$team1_win, .data$team2_win), away_record = ifelse(.data$homeAway == "away",.data$team1_record, .data$team2_record) ) wnba_data <- wnba_data %>% dplyr::mutate_at(c( "game_id", "home_team_id", "home_win", "away_team_id", "away_win", "home_score", "away_score"), as.integer) wnba_data <- wnba_data %>% dplyr::select(-dplyr::any_of(dplyr::starts_with("team1")), -dplyr::any_of(dplyr::starts_with("team2")), -dplyr::any_of(c("homeAway"))) if ("broadcasts" %in% names(wnba_data) && !any(is.na(wnba_data[['broadcasts']]))) { wnba_data %>% tidyr::hoist( "broadcasts", broadcast_market = list(1, "market"), broadcast_name = list(1, "names", 1)) %>% dplyr::select(!where(is.list)) %>% janitor::clean_names() %>% make_wehoop_data("ESPN WNBA Scoreboard Information from ESPN.com",Sys.time()) } else { wnba_data %>% dplyr::select(!where(is.list)) %>% janitor::clean_names() %>% make_wehoop_data("ESPN WNBA Scoreboard Information from ESPN.com",Sys.time()) } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoreboard data available!")) }, warning = function(w) { }, finally = { } ) } #' **Get ESPN WNBA Standings** #' #' @author Geoff Hutchinson #' @param year Either numeric or character (YYYY) #' @return Returns a tibble #' #' |col_name |types | #' |:------------------|:---------| #' |team_id |integer | #' |team |character | #' |avgpointsagainst |numeric | #' |avgpointsfor |numeric | #' |clincher |numeric | #' |differential |numeric | #' |divisionwinpercent |numeric | #' |gamesbehind |numeric | #' |leaguewinpercent |numeric | #' |losses |numeric | #' |playoffseed |numeric | #' |streak |numeric | #' |winpercent |numeric | #' |wins |numeric | #' |leaguestandings |character | #' |home |character | #' |road |character | #' |vsdiv |character | #' |vsconf |character | #' |lasttengames |character | #' #' @importFrom rlang .data #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr select rename #' @importFrom tidyr pivot_wider #' @importFrom data.table rbindlist #' @keywords WNBA Standings #' @family ESPN WNBA Functions #' @export #' @examples #' \donttest{ #' try(espn_wnba_standings(year = 2021)) #' } espn_wnba_standings <- function(year){ standings_url <- "https://site.web.api.espn.com/apis/v2/sports/basketball/wnba/standings?region=us&lang=en&contentorigin=espn&type=0&level=1&sort=winpercent%3Adesc%2Cwins%3Adesc%2Cgamesbehind%3Aasc&" ## Inputs ## year full_url <- paste0(standings_url, "season=", year) res <- httr::RETRY("GET", full_url) # Check the result check_status(res) tryCatch( expr = { resp <- res %>% httr::content(as = "text", encoding = "UTF-8") raw_standings <- jsonlite::fromJSON(resp)[["standings"]] #Create a dataframe of all NBA teams by extracting from the raw_standings file teams <- raw_standings[["entries"]][["team"]] teams <- teams %>% dplyr::select( "id", "displayName") %>% dplyr::rename( "team_id" = "id", "team" = "displayName") #creating a dataframe of the WNBA raw standings table from ESPN standings_df <- raw_standings[["entries"]][["stats"]] standings_data <- data.table::rbindlist(standings_df, fill = TRUE, idcol = T) #Use the following code to replace NA's in the dataframe with the correct corresponding values and removing all unnecessary columns standings_data$value <- ifelse(is.na(standings_data$value) & !is.na(standings_data$summary), standings_data$summary, standings_data$value) standings_data <- standings_data %>% dplyr::select( ".id", "type", "value") #Use pivot_wider to transpose the dataframe so that we now have a standings row for each team standings_data <- standings_data %>% tidyr::pivot_wider(names_from = "type", values_from = "value") standings_data <- standings_data %>% dplyr::select(-".id") #joining the 2 dataframes together to create a standings table standings <- cbind(teams, standings_data) %>% dplyr::mutate(team_id = as.integer(.data$team_id)) %>% dplyr::mutate_at(c( "avgpointsagainst", "avgpointsfor", "clincher", "differential", "divisionwinpercent", "gamesbehind", "leaguewinpercent", "losses", "playoffseed", "streak", "winpercent", "wins" ), as.numeric) %>% make_wehoop_data("ESPN WNBA Standings Information from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no standings data available!")) }, warning = function(w) { }, finally = { } ) return(standings) } #' @import utils utils::globalVariables(c("where")) #' @title #' **Get ESPN WNBA team stats data** #' @author Saiem Gilani #' @param team_id Team ID #' @param year Year #' @param season_type (character, default: regular): Season type - regular or postseason #' @param total (boolean, default: FALSE): Totals #' @return Returns a tibble with the team stats data #' #' |col_name |types | #' |:------------------------------------------------|:---------| #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_is_active |logical | #' |team_is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' |defensive_blocks |numeric | #' |defensive_defensive_rebounds |numeric | #' |defensive_steals |numeric | #' |defensive_avg_defensive_rebounds |numeric | #' |defensive_avg_blocks |numeric | #' |defensive_avg_steals |numeric | #' |defensive_avg48defensive_rebounds |numeric | #' |defensive_avg48blocks |numeric | #' |defensive_avg48steals |numeric | #' |general_disqualifications |numeric | #' |general_flagrant_fouls |numeric | #' |general_fouls |numeric | #' |general_ejections |numeric | #' |general_technical_fouls |numeric | #' |general_rebounds |numeric | #' |general_avg_minutes |numeric | #' |general_nba_rating |numeric | #' |general_plus_minus |numeric | #' |general_game_day_of_year |numeric | #' |general_avg_rebounds |numeric | #' |general_avg_fouls |numeric | #' |general_avg_flagrant_fouls |numeric | #' |general_avg_technical_fouls |numeric | #' |general_avg_ejections |numeric | #' |general_avg_disqualifications |numeric | #' |general_assist_turnover_ratio |numeric | #' |general_steal_foul_ratio |numeric | #' |general_block_foul_ratio |numeric | #' |general_avg_team_rebounds |numeric | #' |general_total_rebounds |numeric | #' |general_total_technical_fouls |numeric | #' |general_team_assist_turnover_ratio |numeric | #' |general_team_rebounds |numeric | #' |general_steal_turnover_ratio |numeric | #' |general_avg48rebounds |numeric | #' |general_avg48fouls |numeric | #' |general_avg48flagrant_fouls |numeric | #' |general_avg48technical_fouls |numeric | #' |general_avg48ejections |numeric | #' |general_avg48disqualifications |numeric | #' |general_games_played |numeric | #' |general_games_started |numeric | #' |general_double_double |numeric | #' |general_triple_double |numeric | #' |offensive_assists |numeric | #' |offensive_field_goals |numeric | #' |offensive_field_goals_attempted |numeric | #' |offensive_field_goals_made |numeric | #' |offensive_field_goal_pct |numeric | #' |offensive_free_throws |numeric | #' |offensive_free_throw_pct |numeric | #' |offensive_free_throws_attempted |numeric | #' |offensive_free_throws_made |numeric | #' |offensive_offensive_rebounds |numeric | #' |offensive_points |numeric | #' |offensive_turnovers |numeric | #' |offensive_three_point_pct |numeric | #' |offensive_three_point_field_goals_attempted |numeric | #' |offensive_three_point_field_goals_made |numeric | #' |offensive_team_turnovers |numeric | #' |offensive_total_turnovers |numeric | #' |offensive_points_in_paint |numeric | #' |offensive_brick_index |numeric | #' |offensive_avg_field_goals_made |numeric | #' |offensive_avg_field_goals_attempted |numeric | #' |offensive_avg_three_point_field_goals_made |numeric | #' |offensive_avg_three_point_field_goals_attempted |numeric | #' |offensive_avg_free_throws_made |numeric | #' |offensive_avg_free_throws_attempted |numeric | #' |offensive_avg_points |numeric | #' |offensive_avg_points_allowed |numeric | #' |offensive_avg_offensive_rebounds |numeric | #' |offensive_avg_assists |numeric | #' |offensive_avg_turnovers |numeric | #' |offensive_offensive_rebound_pct |numeric | #' |offensive_estimated_possessions |numeric | #' |offensive_avg_estimated_possessions |numeric | #' |offensive_points_per_estimated_possessions |numeric | #' |offensive_avg_team_turnovers |numeric | #' |offensive_avg_total_turnovers |numeric | #' |offensive_three_point_field_goal_pct |numeric | #' |offensive_two_point_field_goals_made |numeric | #' |offensive_two_point_field_goals_attempted |numeric | #' |offensive_avg_two_point_field_goals_made |numeric | #' |offensive_avg_two_point_field_goals_attempted |numeric | #' |offensive_two_point_field_goal_pct |numeric | #' |offensive_shooting_efficiency |numeric | #' |offensive_scoring_efficiency |numeric | #' |offensive_avg48field_goals_made |numeric | #' |offensive_avg48field_goals_attempted |numeric | #' |offensive_avg48three_point_field_goals_made |numeric | #' |offensive_avg48three_point_field_goals_attempted |numeric | #' |offensive_avg48free_throws_made |numeric | #' |offensive_avg48free_throws_attempted |numeric | #' |offensive_avg48points |numeric | #' |offensive_avg48offensive_rebounds |numeric | #' |offensive_avg48assists |numeric | #' |offensive_avg48turnovers |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows #' @importFrom tidyr unnest unnest_wider everything #' @export #' @keywords WNBA Team Stats #' @family ESPN WNBA Functions #' #' @examples #' \donttest{ #' try(espn_wnba_team_stats(team_id = 18, year = 2020)) #' } espn_wnba_team_stats <- function( team_id, year, season_type = 'regular', total = FALSE ){ if (!(tolower(season_type) %in% c("regular","postseason"))) { # Check if season_type is appropriate, if not regular cli::cli_abort("Enter valid season_type: regular or postseason") } s_type <- ifelse(season_type == "postseason", 3, 2) base_url <- "https://sports.core.api.espn.com/v2/sports/basketball/leagues/wnba/seasons/" totals <- ifelse(total == TRUE, 0, "") full_url <- paste0( base_url, year, '/types/',s_type, '/teams/',team_id, '/statistics/', totals ) df <- data.frame() tryCatch( expr = { # Create the GET request and set response as res res <- httr::RETRY("GET", full_url) # Check the result check_status(res) # Get the content and return result as data.frame df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() team_url <- df[["team"]][["$ref"]] # Create the GET request and set response as res team_res <- httr::RETRY("GET", team_url) # Check the result check_status(team_res) # Get the content and return result as data.frame team_df <- team_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["record"]] <- NULL team_df[["college"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list,as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.lastUpdated.1", "X.ref", "X.ref.1", "X.ref.2", "X.ref.3"))) %>% janitor::clean_names() colnames(team_df)[1:14] <- paste0("team_",colnames(team_df)[1:14]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") df <- df %>% purrr::pluck("splits") %>% purrr::pluck("categories") %>% tidyr::unnest("stats", names_sep = "_") df <- df %>% dplyr::mutate( stats_category_name = glue::glue("{.data$name}_{.data$stats_name}")) %>% dplyr::select( "stats_category_name", "stats_value") %>% tidyr::pivot_wider( names_from = "stats_category_name", values_from = "stats_value", values_fn = dplyr::first) %>% janitor::clean_names() df <- team_df %>% dplyr::bind_cols(df) df <- df %>% dplyr::mutate_at(c( "team_id", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WNBA Team Season Stats from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}:Invalid arguments or no team season stats data available!")) }, warning = function(w) { }, finally = { } ) return(df) } #' @title #' **Get ESPN WNBA player stats data** #' @author Saiem Gilani #' @param athlete_id Athlete ID #' @param year Year #' @param season_type (character, default: regular): Season type - regular or postseason #' @param total (boolean, default: FALSE): Totals #' @return Returns a tibble with the player stats data #' #' |col_name |types | #' |:------------------------------------------------|:---------| #' |athlete_id |integer | #' |athlete_uid |character | #' |athlete_guid |character | #' |athlete_type |character | #' |sdr |integer | #' |first_name |character | #' |last_name |character | #' |full_name |character | #' |display_name |character | #' |short_name |character | #' |weight |numeric | #' |display_weight |character | #' |height |numeric | #' |display_height |character | #' |age |integer | #' |date_of_birth |character | #' |slug |character | #' |headshot_href |character | #' |headshot_alt |character | #' |position_id |integer | #' |position_name |character | #' |position_display_name |character | #' |position_abbreviation |character | #' |position_leaf |logical | #' |linked |logical | #' |years |integer | #' |active |logical | #' |status_id |integer | #' |status_name |character | #' |status_type |character | #' |status_abbreviation |character | #' |defensive_blocks |numeric | #' |defensive_defensive_rebounds |numeric | #' |defensive_steals |numeric | #' |defensive_avg_defensive_rebounds |numeric | #' |defensive_avg_blocks |numeric | #' |defensive_avg_steals |numeric | #' |defensive_avg48defensive_rebounds |numeric | #' |defensive_avg48blocks |numeric | #' |defensive_avg48steals |numeric | #' |general_disqualifications |numeric | #' |general_flagrant_fouls |numeric | #' |general_fouls |numeric | #' |general_ejections |numeric | #' |general_technical_fouls |numeric | #' |general_rebounds |numeric | #' |general_vorp |numeric | #' |general_minutes |numeric | #' |general_avg_minutes |numeric | #' |general_fantasy_rating |numeric | #' |general_nba_rating |numeric | #' |general_plus_minus |numeric | #' |general_avg_rebounds |numeric | #' |general_avg_fouls |numeric | #' |general_avg_flagrant_fouls |numeric | #' |general_avg_technical_fouls |numeric | #' |general_avg_ejections |numeric | #' |general_avg_disqualifications |numeric | #' |general_assist_turnover_ratio |numeric | #' |general_steal_foul_ratio |numeric | #' |general_block_foul_ratio |numeric | #' |general_avg_team_rebounds |numeric | #' |general_total_rebounds |numeric | #' |general_total_technical_fouls |numeric | #' |general_team_assist_turnover_ratio |numeric | #' |general_steal_turnover_ratio |numeric | #' |general_avg48rebounds |numeric | #' |general_avg48fouls |numeric | #' |general_avg48flagrant_fouls |numeric | #' |general_avg48technical_fouls |numeric | #' |general_avg48ejections |numeric | #' |general_avg48disqualifications |numeric | #' |general_games_played |numeric | #' |general_games_started |numeric | #' |general_double_double |numeric | #' |general_triple_double |numeric | #' |offensive_assists |numeric | #' |offensive_field_goals |numeric | #' |offensive_field_goals_attempted |numeric | #' |offensive_field_goals_made |numeric | #' |offensive_field_goal_pct |numeric | #' |offensive_free_throws |numeric | #' |offensive_free_throw_pct |numeric | #' |offensive_free_throws_attempted |numeric | #' |offensive_free_throws_made |numeric | #' |offensive_offensive_rebounds |numeric | #' |offensive_points |numeric | #' |offensive_turnovers |numeric | #' |offensive_three_point_pct |numeric | #' |offensive_three_point_field_goals_attempted |numeric | #' |offensive_three_point_field_goals_made |numeric | #' |offensive_total_turnovers |numeric | #' |offensive_points_in_paint |numeric | #' |offensive_brick_index |numeric | #' |offensive_avg_field_goals_made |numeric | #' |offensive_avg_field_goals_attempted |numeric | #' |offensive_avg_three_point_field_goals_made |numeric | #' |offensive_avg_three_point_field_goals_attempted |numeric | #' |offensive_avg_free_throws_made |numeric | #' |offensive_avg_free_throws_attempted |numeric | #' |offensive_avg_points |numeric | #' |offensive_avg_offensive_rebounds |numeric | #' |offensive_avg_assists |numeric | #' |offensive_avg_turnovers |numeric | #' |offensive_offensive_rebound_pct |numeric | #' |offensive_estimated_possessions |numeric | #' |offensive_avg_estimated_possessions |numeric | #' |offensive_points_per_estimated_possessions |numeric | #' |offensive_avg_team_turnovers |numeric | #' |offensive_avg_total_turnovers |numeric | #' |offensive_three_point_field_goal_pct |numeric | #' |offensive_two_point_field_goals_made |numeric | #' |offensive_two_point_field_goals_attempted |numeric | #' |offensive_avg_two_point_field_goals_made |numeric | #' |offensive_avg_two_point_field_goals_attempted |numeric | #' |offensive_two_point_field_goal_pct |numeric | #' |offensive_shooting_efficiency |numeric | #' |offensive_scoring_efficiency |numeric | #' |offensive_avg48field_goals_made |numeric | #' |offensive_avg48field_goals_attempted |numeric | #' |offensive_avg48three_point_field_goals_made |numeric | #' |offensive_avg48three_point_field_goals_attempted |numeric | #' |offensive_avg48free_throws_made |numeric | #' |offensive_avg48free_throws_attempted |numeric | #' |offensive_avg48points |numeric | #' |offensive_avg48offensive_rebounds |numeric | #' |offensive_avg48assists |numeric | #' |offensive_avg48turnovers |numeric | #' |team_id |integer | #' |team_guid |character | #' |team_uid |character | #' |team_sdr |integer | #' |team_slug |character | #' |team_location |character | #' |team_name |character | #' |team_abbreviation |character | #' |team_display_name |character | #' |team_short_display_name |character | #' |team_color |character | #' |team_alternate_color |character | #' |team_is_active |logical | #' |team_is_all_star |logical | #' |logo_href |character | #' |logo_dark_href |character | #' #' @export #' @keywords WNBA Player Stats #' @family ESPN WNBA Functions #' #' @examples #' \donttest{ #' try(espn_wnba_player_stats(athlete_id = 2529130, year = 2022)) #' } espn_wnba_player_stats <- function( athlete_id, year, season_type = 'regular', total = FALSE ){ if (!(tolower(season_type) %in% c("regular","postseason"))) { # Check if season_type is appropriate, if not regular cli::cli_abort("Enter valid season_type: regular or postseason") } s_type <- ifelse(season_type == "postseason", 3, 2) base_url <- "https://sports.core.api.espn.com/v2/sports/basketball/leagues/wnba/seasons/" totals <- ifelse(total == TRUE, 0, "") full_url <- paste0( base_url, year, '/types/',s_type, '/athletes/', athlete_id, '/statistics/', totals ) athlete_url <- paste0( base_url, year, '/athletes/', athlete_id ) df <- data.frame() tryCatch( expr = { # Create the GET request and set response as res res <- httr::RETRY("GET", full_url) # Check the result check_status(res) # Create the GET request and set response as res athlete_res <- httr::RETRY("GET", athlete_url) # Check the result check_status(athlete_res) athlete_df <- athlete_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_url <- athlete_df[["team"]][["$ref"]] # Create the GET request and set response as res team_res <- httr::RETRY("GET", team_url) # Check the result check_status(team_res) team_df <- team_res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON(simplifyDataFrame = FALSE, simplifyVector = FALSE, simplifyMatrix = FALSE) team_df[["links"]] <- NULL team_df[["injuries"]] <- NULL team_df[["record"]] <- NULL team_df[["athletes"]] <- NULL team_df[["venue"]] <- NULL team_df[["groups"]] <- NULL team_df[["ranks"]] <- NULL team_df[["statistics"]] <- NULL team_df[["leaders"]] <- NULL team_df[["links"]] <- NULL team_df[["notes"]] <- NULL team_df[["franchise"]] <- NULL team_df[["record"]] <- NULL team_df[["college"]] <- NULL team_df <- team_df %>% purrr::map_if(is.list,as.data.frame) %>% as.data.frame() %>% dplyr::select( -dplyr::any_of( c("logos.width", "logos.height", "logos.alt", "logos.rel..full.", "logos.rel..default.", "logos.lastUpdated", "logos.width.1", "logos.height.1", "logos.alt.1", "logos.rel..full..1", "logos.rel..dark.", "logos.lastUpdated.1", "X.ref", "X.ref.1", "X.ref.2", "X.ref.3"))) %>% janitor::clean_names() colnames(team_df)[1:14] <- paste0("team_",colnames(team_df)[1:14]) team_df <- team_df %>% dplyr::rename( "logo_href" = "logos_href", "logo_dark_href" = "logos_href_1") athlete_df[["links"]] <- NULL athlete_df[["injuries"]] <- NULL athlete_df[["birthPlace"]] <- NULL athlete_df <- athlete_df %>% purrr::map_if(is.list, as.data.frame) %>% tibble::tibble(data = .data$.) athlete_df <- athlete_df$data %>% as.data.frame() %>% dplyr::select(-dplyr::any_of(c("X.ref","X.ref.1","X.ref.2","X.ref.3","X.ref.4","X.ref.5","X.ref.6","X.ref.7","position.X.ref"))) %>% janitor::clean_names() %>% dplyr::rename( "athlete_id" = "id", "athlete_uid" = "uid", "athlete_guid" = "guid", "athlete_type" = "type") # Get the content and return result as data.frame df <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() %>% purrr::pluck("splits") %>% purrr::pluck("categories") %>% tidyr::unnest("stats", names_sep = "_") df <- df %>% dplyr::mutate( stats_category_name = glue::glue("{.data$name}_{.data$stats_name}")) %>% dplyr::select( "stats_category_name", "stats_value") %>% tidyr::pivot_wider( names_from = "stats_category_name", values_from = "stats_value", values_fn = dplyr::first) %>% janitor::clean_names() df <- athlete_df %>% dplyr::bind_cols(df) %>% dplyr::bind_cols(team_df) df <- df %>% dplyr::mutate_at(c( "athlete_id", "team_id", "position_id", "status_id", "sdr", "team_sdr"), as.integer) %>% make_wehoop_data("ESPN WNBA Player Season Stats from ESPN.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}:Invalid arguments or no player season stats data available!")) }, warning = function(w) { }, finally = { } ) return(df) } #' **Parse ESPN WNBA PBP, helper function** #' @param resp Response object from the ESPN WNBA game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wnba_pbp <- function(resp){ game_json <- resp %>% jsonlite::fromJSON() pbp_source <- game_json[["header"]][["competitions"]][["playByPlaySource"]] plays <- game_json %>% purrr::pluck("plays") %>% dplyr::as_tibble() if (pbp_source != "none" && nrow(plays) > 10) { homeAway1 <- jsonlite::fromJSON(resp)[['header']][['competitions']][['competitors']][[1]][['homeAway']][1] gameId <- as.integer(game_json[["header"]][["id"]]) season <- game_json[['header']][['season']][['year']] season_type <- game_json[['header']][['season']][['type']] game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) id_vars <- data.frame() if (homeAway1 == "home") { homeTeamId = as.integer(game_json[["header"]][["competitions"]][["competitors"]][[1]][['team']][['id']] %>% purrr::pluck(1, .default = NA_integer_)) homeTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(1, .default = NA_character_) homeTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(1, .default = NA_character_) homeTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(1, .default = NA_character_) homeTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(1, .default = NA_character_) homeTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) homeTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(1, .default = NA_character_)) homeTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(1, .default = NA_character_) homeTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(1, .default = NA_character_) awayTeamId = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['team']][['id']] %>% purrr::pluck(2, .default = NA_integer_)) awayTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(2, .default = NA_character_) awayTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(2, .default = NA_character_) awayTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(2, .default = NA_character_) awayTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) awayTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) awayTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(2, .default = NA_integer_)) awayTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(2, .default = NA_character_) awayTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(2, .default = NA_character_) id_vars <- data.frame( homeTeamId, homeTeamMascot, homeTeamName, homeTeamAbbrev, homeTeamLogo, homeTeamLogoDark, homeTeamFullName, homeTeamColor, homeTeamAlternateColor, homeTeamScore, homeTeamWinner, homeTeamRecord, awayTeamId, awayTeamMascot, awayTeamName, awayTeamAbbrev, awayTeamLogo, awayTeamLogoDark, awayTeamFullName, awayTeamColor, awayTeamAlternateColor, awayTeamScore, awayTeamWinner, awayTeamRecord ) } else { awayTeamId = as.integer(game_json[["header"]][["competitions"]][["competitors"]][[1]][['team']][['id']] %>% purrr::pluck(1, .default = NA_integer_)) awayTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(1, .default = NA_character_) awayTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(1, .default = NA_character_) awayTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(1, .default = NA_character_) awayTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[1]][['href']] %>% purrr::pluck(2, .default = NA_character_) awayTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) awayTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(1, .default = NA_integer_)) awayTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(1, .default = NA_character_) awayTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(1, .default = NA_character_) homeTeamId = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['team']][['id']] %>% purrr::pluck(2, .default = NA_integer_)) homeTeamMascot = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['name']] %>% purrr::pluck(2, .default = NA_character_) homeTeamName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['location']] %>% purrr::pluck(2, .default = NA_character_) homeTeamAbbrev = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['abbreviation']] %>% purrr::pluck(2, .default = NA_character_) homeTeamLogo = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamLogoDark = game_json[['header']][['competitions']][['competitors']][[1]][['team']][['logos']][[2]][['href']] %>% purrr::pluck(2, .default = NA_character_) homeTeamFullName = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["displayName"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["color"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamAlternateColor = game_json[['header']][['competitions']][['competitors']][[1]][['team']][["alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) homeTeamScore = as.integer(game_json[['header']][['competitions']][['competitors']][[1]][['score']] %>% purrr::pluck(2, .default = NA_integer_)) homeTeamWinner = game_json[['header']][['competitions']][['competitors']][[1]][['winner']] %>% purrr::pluck(2, .default = NA_character_) homeTeamRecord = game_json[['header']][['competitions']][['competitors']][[1]][['record']][[1]][['summary']] %>% purrr::pluck(2, .default = NA_character_) id_vars <- data.frame( homeTeamId, homeTeamMascot, homeTeamName, homeTeamAbbrev, homeTeamLogo, homeTeamLogoDark, homeTeamFullName, homeTeamColor, homeTeamAlternateColor, homeTeamScore, homeTeamWinner, homeTeamRecord, awayTeamId, awayTeamMascot, awayTeamName, awayTeamAbbrev, awayTeamLogo, awayTeamLogoDark, awayTeamFullName, awayTeamColor, awayTeamAlternateColor, awayTeamScore, awayTeamWinner, awayTeamRecord ) } game_json <- game_json %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) plays <- game_json %>% purrr::pluck("plays") if (("coordinate.x" %in% names(plays)) && ("coordinate.y" %in% names(plays))) { plays <- plays %>% dplyr::mutate( # convert types coordinate.x = as.double(.data$coordinate.x), coordinate.y = as.double(.data$coordinate.y), # Free throws are adjusted automatically to 19' from baseline, which # corresponds to 13.75' from the center of the basket (originally # the center of the basket is (25, 0)) coordinate.y = dplyr::case_when( stringr::str_detect(.data$type.text, "Free Throw") ~ 13.75, TRUE ~ .data$coordinate.y ), coordinate.x = dplyr::case_when( stringr::str_detect(.data$type.text, "Free Throw") ~ 25, TRUE ~ .data$coordinate.x ), coordinate_x_transformed = dplyr::case_when( .data$team.id == homeTeamId ~ -1 * (.data$coordinate.y - 41.75), TRUE ~ .data$coordinate.y - 41.75 ), coordinate_y_transformed = dplyr::case_when( .data$team.id == homeTeamId ~ -1 * (.data$coordinate.x - 25), TRUE ~ .data$coordinate.x - 25 ) ) %>% dplyr::rename( "coordinate.x.raw" = "coordinate.x", "coordinate.y.raw" = "coordinate.y", "coordinate.x" = "coordinate_x_transformed", "coordinate.y" = "coordinate_y_transformed" ) } ## Written this way for compliance with data repository processing if ("participants" %in% names(plays)) { plays <- plays %>% tidyr::unnest_wider("participants") suppressWarnings( aths <- plays %>% dplyr::group_by(.data$id) %>% dplyr::select( "id", "athlete.id") %>% tidyr::unnest_wider("athlete.id", names_sep = "_") ) names(aths) <- c("play.id", "athlete.id.1", "athlete.id.2", "athlete.id.3") plays <- plays %>% dplyr::bind_cols(aths) %>% janitor::clean_names() %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "athlete_id_1", "athlete_id_2", "athlete_id_3" )), ~as.integer(.x))) } ## Written this way for compliance with data repository processing if (!("homeTeamName" %in% names(plays))) { plays <- plays %>% dplyr::bind_cols(id_vars) } plays <- plays %>% dplyr::select(-dplyr::any_of(c("athlete.id", "athlete_id"))) %>% janitor::clean_names() %>% dplyr::mutate( game_id = gameId, season = season, season_type = season_type, game_date = game_date, game_date_time = game_date_time) %>% dplyr::rename(dplyr::any_of(c( "athlete_id_1" = "participants_0_athlete_id", "athlete_id_2" = "participants_1_athlete_id", "athlete_id_3" = "participants_2_athlete_id"))) plays <- plays %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "athlete_id_1", "athlete_id_2", "athlete_id_3", "type_id", "team_id" )), ~as.integer(.x))) plays_df <- plays %>% make_wehoop_data("ESPN WNBA Play-by-Play Information from ESPN.com", Sys.time()) return(plays_df) } } #' **Parse ESPN WNBA Team Box, helper function** #' @param resp Response object from the ESPN WNBA game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wnba_team_box <- function(resp){ game_json <- resp %>% jsonlite::fromJSON() gameId <- as.integer(game_json[["header"]][["id"]]) game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) box_score_available <- game_json[["header"]][["competitions"]][["boxscoreAvailable"]] if (box_score_available == TRUE) { teams_box_score_df <- game_json[["boxscore"]][["teams"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) if (length(teams_box_score_df[["statistics"]][[1]]) > 0) { # Teams info columns and values teams_df <- game_json[["header"]][["competitions"]][["competitors"]][[1]] homeAway1 <- teams_df[["homeAway"]][1] homeAway1_team.id <- as.integer(teams_df[["id"]][1]) homeAway1_team.score <- as.integer(teams_df[["score"]][1]) homeAway1_team.winner <- teams_df[["winner"]][1] homeAway2 <- teams_df[["homeAway"]][2] homeAway2_team.id <- as.integer(teams_df[["id"]][2]) homeAway2_team.score <- as.integer(teams_df[["score"]][2]) homeAway2_team.winner <- teams_df[["winner"]][2] # Pivoting the table values for each team from long to wide statistics_df_1 <- teams_box_score_df[["statistics"]][[1]] %>% tibble::tibble() %>% dplyr::select("name", "displayValue") %>% tidyr::spread("name", "displayValue") statistics_df_2 <- teams_box_score_df[["statistics"]][[2]] %>% tibble::tibble() %>% dplyr::select("name", "displayValue") %>% tidyr::spread("name", "displayValue") # Assigning values to the correct data frame rows - 1 statistics_df_1$team.homeAway <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), homeAway1, homeAway2 ) statistics_df_1$team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), as.integer(homeAway1_team.score), as.integer(homeAway2_team.score) ) statistics_df_1$team.winner <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), homeAway1_team.winner, homeAway2_team.winner ) statistics_df_1$team.id <- as.integer(teams_box_score_df[["team.id"]][[1]]) statistics_df_1$team.uid <- teams_box_score_df[["team.uid"]][[1]] statistics_df_1$team.slug <- teams_box_score_df[["team.slug"]][[1]] statistics_df_1$team.location <- teams_box_score_df[["team.location"]][[1]] statistics_df_1$team.name <- teams_box_score_df[["team.name"]][[1]] statistics_df_1$team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[1]] statistics_df_1$team.displayName <- teams_box_score_df[["team.displayName"]][[1]] statistics_df_1$team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[1]] statistics_df_1$team.color <- teams_box_score_df[["team.color"]][[1]] statistics_df_1$team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[1]] statistics_df_1$team.logo <- teams_box_score_df[["team.logo"]][[1]] statistics_df_1$opponent.team.id <- as.integer(teams_box_score_df[["team.id"]][[2]]) statistics_df_1$opponent.team.uid <- teams_box_score_df[["team.uid"]][[2]] statistics_df_1$opponent.team.slug <- teams_box_score_df[["team.slug"]][[2]] statistics_df_1$opponent.team.location <- teams_box_score_df[["team.location"]][[2]] statistics_df_1$opponent.team.name <- teams_box_score_df[["team.name"]][[2]] statistics_df_1$opponent.team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[2]] statistics_df_1$opponent.team.displayName <- teams_box_score_df[["team.displayName"]][[2]] statistics_df_1$opponent.team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[2]] statistics_df_1$opponent.team.color <- teams_box_score_df[["team.color"]][[2]] statistics_df_1$opponent.team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[2]] statistics_df_1$opponent.team.logo <- teams_box_score_df[["team.logo"]][[2]] statistics_df_1$opponent.team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][1]) == as.integer(homeAway1_team.id), as.integer(homeAway2_team.score), as.integer(homeAway1_team.score) ) # Assigning values to the correct data frame rows - 2 statistics_df_2$team.homeAway <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), homeAway2, homeAway1 ) statistics_df_2$team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), as.integer(homeAway2_team.score), as.integer(homeAway1_team.score) ) statistics_df_2$team.winner <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), homeAway2_team.winner, homeAway1_team.winner ) statistics_df_2$team.id <- as.integer(teams_box_score_df[["team.id"]][[2]]) statistics_df_2$team.uid <- teams_box_score_df[["team.uid"]][[2]] statistics_df_2$team.slug <- teams_box_score_df[["team.slug"]][[2]] statistics_df_2$team.location <- teams_box_score_df[["team.location"]][[2]] statistics_df_2$team.name <- teams_box_score_df[["team.name"]][[2]] statistics_df_2$team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[2]] statistics_df_2$team.displayName <- teams_box_score_df[["team.displayName"]][[2]] statistics_df_2$team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[2]] statistics_df_2$team.color <- teams_box_score_df[["team.color"]][[2]] statistics_df_2$team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[2]] statistics_df_2$team.logo <- teams_box_score_df[["team.logo"]][[2]] statistics_df_2$opponent.team.id <- as.integer(teams_box_score_df[["team.id"]][[1]]) statistics_df_2$opponent.team.uid <- teams_box_score_df[["team.uid"]][[1]] statistics_df_2$opponent.team.slug <- teams_box_score_df[["team.slug"]][[1]] statistics_df_2$opponent.team.location <- teams_box_score_df[["team.location"]][[1]] statistics_df_2$opponent.team.name <- teams_box_score_df[["team.name"]][[1]] statistics_df_2$opponent.team.abbreviation <- teams_box_score_df[["team.abbreviation"]][[1]] statistics_df_2$opponent.team.displayName <- teams_box_score_df[["team.displayName"]][[1]] statistics_df_2$opponent.team.shortDisplayName <- teams_box_score_df[["team.shortDisplayName"]][[1]] statistics_df_2$opponent.team.color <- teams_box_score_df[["team.color"]][[1]] statistics_df_2$opponent.team.alternateColor <- teams_box_score_df[["team.alternateColor"]][[1]] statistics_df_2$opponent.team.logo <- teams_box_score_df[["team.logo"]][[1]] statistics_df_2$opponent.team.score <- ifelse( as.integer(teams_box_score_df[["team.id"]][2]) == as.integer(homeAway2_team.id), as.integer(homeAway1_team.score), as.integer(homeAway2_team.score) ) complete_statistics_df <- statistics_df_1 %>% dplyr::bind_rows(statistics_df_2) # Assigning game/season level data to team box score and converting types complete_statistics_df$season <- game_json[["header"]][["season"]][["year"]] complete_statistics_df$season_type <- game_json[["header"]][["season"]][["type"]] complete_statistics_df$game_date <- as.Date(substr(game_json[["header"]][["competitions"]][["date"]], 0, 10)) complete_statistics_df$game_id <- as.integer(gameId) complete_statistics_df$game_date_time <- game_date_time complete_statistics_df$game_date <- game_date suppressWarnings( complete_statistics_df <- complete_statistics_df %>% tidyr::separate("fieldGoalsMade-fieldGoalsAttempted", into = c("fieldGoalsMade", "fieldGoalsAttempted"), sep = "-") %>% tidyr::separate("freeThrowsMade-freeThrowsAttempted", into = c("freeThrowsMade", "freeThrowsAttempted"), sep = "-") %>% tidyr::separate("threePointFieldGoalsMade-threePointFieldGoalsAttempted", into = c("threePointFieldGoalsMade", "threePointFieldGoalsAttempted"), sep = "-") %>% dplyr::mutate(dplyr::across(c( "fieldGoalPct", "freeThrowPct", "threePointFieldGoalPct" ), ~as.numeric(.x))) %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "assists", "blocks", "defensiveRebounds", "fieldGoalsMade", "fieldGoalsAttempted", "flagrantFouls", "fouls", "freeThrowsMade", "freeThrowsAttempted", "offensiveRebounds", "steals", "teamTurnovers", "technicalFouls", "threePointFieldGoalsMade", "threePointFieldGoalsAttempted", "totalRebounds", "totalTechnicalFouls", "totalTurnovers", "turnovers" )), ~as.integer(.x))) ) team_box_score <- complete_statistics_df %>% janitor::clean_names() %>% dplyr::select(dplyr::any_of(c( "game_id", "season", "season_type", "game_date", "game_date_time", "team_id", "team_uid", "team_slug", "team_location", "team_name", "team_abbreviation", "team_display_name", "team_short_display_name", "team_color", "team_alternate_color", "team_logo", "team_home_away", "team_score", "team_winner")), tidyr::everything()) %>% make_wehoop_data("ESPN WNBA Team Box Information from ESPN.com", Sys.time()) return(team_box_score) } } } #' **Parse ESPN WNBA Player Box, helper function** #' @param resp Response object from the ESPN WNBA game summary endpoint #' @return Returns a tibble #' @importFrom lubridate with_tz ymd_hm #' @export helper_espn_wnba_player_box <- function(resp){ game_json <- resp %>% jsonlite::fromJSON(flatten = TRUE) players_box_score_df <- game_json[["boxscore"]][["players"]] %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) %>% as.data.frame() gameId <- as.integer(game_json[["header"]][["id"]]) season <- game_json[["header"]][["season"]][["year"]] season_type <- game_json[["header"]][["season"]][["type"]] game_date_time <- substr(game_json[['header']][['competitions']][['date']], 1, nchar(game_json[['header']][['competitions']][['date']]) - 1) %>% lubridate::ymd_hm() %>% lubridate::with_tz(tzone = "America/New_York") game_date <- as.Date(substr(game_date_time, 0, 10)) boxScoreAvailable <- game_json[["header"]][["competitions"]][["boxscoreAvailable"]] boxScoreSource <- game_json[["header"]][["competitions"]][["boxscoreSource"]] # This is checking if [[athletes]][[1]]'s stat rebounds is able to be converted to a numeric value # without introducing NA's suppressWarnings( valid_stats <- players_box_score_df[["statistics"]][[1]][["athletes"]][[1]][["stats"]][[1]] %>% purrr::pluck(7) %>% as.numeric() ) if (boxScoreAvailable == TRUE && length(players_box_score_df[["statistics"]][[1]][["athletes"]][[1]]) > 1 && !is.na(valid_stats)) { players_df <- players_box_score_df %>% tidyr::unnest("statistics") %>% tidyr::unnest("athletes") if (length(players_box_score_df[["statistics"]]) > 1 && length(players_df$stats[[1]]) > 0) { players_df <- jsonlite::fromJSON(jsonlite::toJSON(game_json[["boxscore"]][["players"]]), flatten = TRUE) %>% tidyr::unnest("statistics") %>% tidyr::unnest("athletes") stat_cols <- players_df$keys[[1]] stats <- players_df$stats stats_df <- as.data.frame(do.call(rbind,stats)) colnames(stats_df) <- stat_cols suppressWarnings( stats_df <- stats_df %>% tidyr::separate("fieldGoalsMade-fieldGoalsAttempted", into = c("fieldGoalsMade", "fieldGoalsAttempted"), sep = "-") %>% tidyr::separate("freeThrowsMade-freeThrowsAttempted", into = c("freeThrowsMade", "freeThrowsAttempted"), sep = "-") %>% tidyr::separate("threePointFieldGoalsMade-threePointFieldGoalsAttempted", into = c("threePointFieldGoalsMade", "threePointFieldGoalsAttempted"), sep = "-") %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "minutes", "fieldGoalPct", "freeThrowPct", "threePointFieldGoalPct" )), ~as.numeric(.x))) %>% dplyr::mutate(dplyr::across(dplyr::any_of(c( "assists", "blocks", "defensiveRebounds", "fieldGoalsMade", "fieldGoalsAttempted", "flagrantFouls", "fouls", "freeThrowsMade", "freeThrowsAttempted", "offensiveRebounds", "steals", "teamTurnovers", "technicalFouls", "threePointFieldGoalsMade", "threePointFieldGoalsAttempted", "rebounds", "totalTechnicalFouls", "totalTurnovers", "turnovers", "points" )), ~as.integer(.x))) ) players_df_did_not_play <- players_df %>% dplyr::filter(.data$didNotPlay) %>% dplyr::select(dplyr::any_of(c( "starter", "ejected", "didNotPlay", "reason", "active", "athlete.displayName", "athlete.jersey", "athlete.id", "athlete.shortName", "athlete.headshot.href", "athlete.position.name", "athlete.position.abbreviation", "team.displayName", "team.shortDisplayName", "team.location", "team.name", "team.logo", "team.id", "team.uid", "team.slug", "team.abbreviation", "team.color", "team.alternateColor" ))) players_df <- players_df %>% dplyr::filter(!.data$didNotPlay) %>% dplyr::select(dplyr::any_of(c( "starter", "ejected", "didNotPlay", "reason", "active", "athlete.displayName", "athlete.jersey", "athlete.id", "athlete.shortName", "athlete.headshot.href", "athlete.position.name", "athlete.position.abbreviation", "team.displayName", "team.shortDisplayName", "team.location", "team.name", "team.logo", "team.id", "team.uid", "team.slug", "team.abbreviation", "team.color", "team.alternateColor" ))) players_df <- stats_df %>% dplyr::bind_cols(players_df) %>% dplyr::bind_rows(players_df_did_not_play) players_df <- players_df %>% dplyr::select(dplyr::any_of(c( "athlete.displayName", "team.shortDisplayName")), tidyr::everything()) %>% janitor::clean_names() %>% dplyr::mutate( game_id = gameId, season = season, season_type = season_type, game_date = game_date, game_date_time = game_date_time) teams_df <- game_json[["header"]][["competitions"]][["competitors"]][[1]] homeAway1 <- teams_df[["homeAway"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.id <- as.integer(teams_df[["id"]] %>% purrr::pluck(1, .default = NA_integer_)) homeAway1_team.location <- teams_df[["team.location"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.name <- teams_df[["team.name"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.abbreviation <- teams_df[["team.abbreviation"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.displayName <- teams_df[["team.displayName"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.logos <- teams_df[["team.logos"]][[1]][["href"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.color <- teams_df[["team.color"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.alternateColor <- teams_df[["team.alternateColor"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.winner <- teams_df[["winner"]] %>% purrr::pluck(1, .default = NA_character_) homeAway1_team.score <- as.integer(teams_df[["score"]] %>% purrr::pluck(1, .default = NA_integer_)) homeAway2 <- teams_df[["homeAway"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.id <- as.integer(teams_df[["id"]] %>% purrr::pluck(2, .default = NA_integer_)) homeAway2_team.location <- teams_df[["team.location"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.name <- teams_df[["team.name"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.abbreviation <- teams_df[["team.abbreviation"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.displayName <- teams_df[["team.displayName"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.logos <- teams_df[["team.logos"]][[2]][["href"]] %>% purrr::pluck(1, .default = NA_character_) homeAway2_team.color <- teams_df[["team.color"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.alternateColor <- teams_df[["team.alternateColor"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.winner <- teams_df[["winner"]] %>% purrr::pluck(2, .default = NA_character_) homeAway2_team.score <- as.integer(teams_df[["score"]] %>% purrr::pluck(2, .default = NA_integer_)) players_df <- players_df %>% dplyr::mutate( home_away = ifelse(.data$team_id == homeAway1_team.id, homeAway1, homeAway2), team_winner = ifelse(.data$team_id == homeAway1_team.id, homeAway1_team.winner, homeAway2_team.winner), team_score = ifelse(.data$team_id == homeAway1_team.id, homeAway1_team.score, homeAway2_team.score), opponent_team_id = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.id, homeAway1_team.id), opponent_team_name = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.name, homeAway1_team.name), opponent_team_location = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.location, homeAway1_team.location), opponent_team_display_name = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.displayName, homeAway1_team.displayName), opponent_team_abbreviation = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.abbreviation, homeAway1_team.abbreviation), opponent_team_logo = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.logos, homeAway1_team.logos), opponent_team_color = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.color, homeAway1_team.color), opponent_team_alternate_color = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.alternateColor, homeAway1_team.alternateColor), opponent_team_score = ifelse(.data$team_id == homeAway1_team.id, homeAway2_team.score, homeAway1_team.score), ) %>% dplyr::arrange(.data$home_away) player_box_score <- players_df %>% dplyr::select(dplyr::any_of(c( "game_id", "season", "season_type", "game_date", "game_date_time", "athlete_id", "athlete_display_name", "team_id", "team_name", "team_location", "team_short_display_name", "minutes", "field_goals_made", "field_goals_attempted", "three_point_field_goals_made", "three_point_field_goals_attempted", "free_throws_made", "free_throws_attempted", "offensive_rebounds", "defensive_rebounds", "rebounds", "assists", "steals", "blocks", "turnovers", "fouls", "plus_minus", "points", "starter", "ejected", "did_not_play", "reason", "active", "athlete_jersey", "athlete_short_name", "athlete_headshot_href", "athlete_position_name", "athlete_position_abbreviation", "team_display_name", "team_uid", "team_slug", "team_logo", "team_abbreviation", "team_color", "team_alternate_color", "home_away", "team_winner", "team_score", "opponent_team_id", "opponent_team_name", "opponent_team_location", "opponent_team_display_name", "opponent_team_abbreviation", "opponent_team_logo", "opponent_team_color", "opponent_team_alternate_color", "opponent_team_score" ))) %>% dplyr::mutate_at(c( "athlete_id", "team_id", "team_score", "opponent_team_score" ), as.integer) %>% make_wehoop_data("ESPN WNBA Player Box Information from ESPN.com", Sys.time()) return(player_box_score) } } }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/espn_wnba_data.R
#' **Load wehoop women's college basketball play-by-play** #' @name load_wbb_pbp NULL #' @title #' **Load cleaned women's college basketball play-by-play from the data repo** #' @rdname load_wbb_pbp #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given women's college basketball seasons. (Min: 2004) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wbb_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the play by play data table within the database #' @return A dataframe with 55 columns: #' \describe{ #' \item{shooting_play}{Logical value (TRUE/FALSE) indicating whether the play was a shooting play} #' \item{sequence_number}{Sequence number is supposed to represent a shot-possession, examine the last two numbers to see if there are multiple events that occur within the same shot-possession. A shot-possession is basically any sequence of plays until there is a shot, change in possession, and probably things like technical fouls and the like. So as soon as a shot goes up, a new sequence starts regardless, even if the shooting team retains possession via offensive or deadball rebound. The first portion of the number is usually time related (i.e. the numeric representation of when the sequence started, from a seconds remaining in the period perspective or so)} #' \item{period_display_value}{Long form of period (1st quarter, 2nd Quarter, OT, etc.)} #' \item{period_number}{The numeric period of play in the game } #' \item{home_score}{Home score at the time of the play} #' \item{scoring_play}{Logical value (TRUE/FALSE) indicating whether the play was a play on which the offense scored} #' \item{clock_display_value}{Time left within the period} #' \item{team_id}{Unique team identification number for the offensive team} #' \item{type_id}{Unique play type identifcation number} #' \item{type_text}{Play type text description} #' \item{away_score}{Away score at the time of the play} #' \item{id}{Unique play identifcation number} #' \item{text}{Text description of the play} #' \item{score_value}{The points value of the shot taken} #' \item{participants_0_athlete_id}{Unique player identification number } #' \item{participants_1_athlete_id}{Unique player identification number } #' \item{season}{Season of the game} #' \item{season_type}{Season type of the game, 1 is pre-season, 2 is regular season, 3 is post-season, 4 is off-season} #' \item{away_team_id}{Unique away team identification number} #' \item{away_team_name}{Away team name} #' \item{away_team_mascot}{Away team mascot} #' \item{away_team_abbrev}{Text abbreviation for the away team} #' \item{away_team_name_alt}{Alternate versions of the away team abbreviation} #' \item{home_team_id}{Unique home team identification number} #' \item{home_team_name}{home team name} #' \item{home_team_mascot}{home team mascot} #' \item{home_team_abbrev}{Text abbreviation for the home team} #' \item{home_team_name_alt}{Alternate versions of the home team abbreviation} #' \item{home_team_spread}{The game spread with respect to the home team} #' \item{game_spread}{Game spread in (-X Team) format} #' \item{home_favorite}{Logical (TRUE/FALSE) indicating whether the home team is favored} #' \item{game_spread_available}{Logical (TRUE/FALSE) indicating whether the spread was available from ESPN. Basically, I would just not recommend using any of the spread information, I think I defaulted a lot of them to -2.5 for the home team. Most games probably do not have spread information. This column should really be listed first} #' \item{game_id}{Unique identifier for the game event} #' \item{qtr}{Quarter of the game} #' \item{time}{Time left within the period} #' \item{clock_minutes}{Clock minutes split from seconds for developer convenience} #' \item{clock_seconds}{Clock seconds split from minutes for developer convenience} #' \item{half}{Half of the game} #' \item{game_half}{Half of the game} #' \item{lag_qtr}{A lag column on the quarter} #' \item{lead_qtr}{A lead column on the quarter} #' \item{lag_game_half}{A lag column on the half} #' \item{lead_game_half}{A lead column on the half} #' \item{start_quarter_seconds_remaining}{Quarter seconds remaining at the start of the play (these are more or less code artifacts from other sports, but may eventually be used more seriously)} #' \item{start_half_seconds_remaining}{Game half seconds remaining at the start of the play (these are more or less code artifacts from other sports, but may eventually be used more seriously)} #' \item{start_game_seconds_remaining}{Game seconds remaining at the start of the play (''')} #' \item{game_play_number}{Game play number} #' \item{end_quarter_seconds_remaining}{Quarter seconds remaining at the end of the play (''')} #' \item{end_half_seconds_remaining}{Game half seconds remaining at the end of the play (''')} #' \item{end_game_seconds_remaining}{Game seconds remaining at the end of the play (''')} #' \item{period}{Period of the game} #' \item{coordinate_x}{The entire scale is a rectangle of size 25x47, intended as a half-court representation of the basketball court (i.e. on the side of the offense), with each coordinate unit representing a foot. It appears that the basket is roughly represented as the (25, 0) point. This is a nonsensical definition when considering that the basket overhangs the court, with the backboard aligned 48 inches from the baseline, then the center of the hoop being roughly 11 inches from there. This is an idiosyncracy of either sensor placement or software and data entry. Use your best judgement in making your charts, I think you will find that making some translations will be helpful. } #' \item{coordinate_y}{} #' \item{week}{Apparently there are weeks} #' \item{media_id}{Where did you come from} #' } #' @export #' @examples #' \donttest{ #' try(load_wbb_pbp()) #' } load_wbb_pbp <- function(seasons = most_recent_wbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2004:most_recent_wbb_season() stopifnot(is.numeric(seasons), seasons >= 2004, seasons <= most_recent_wbb_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_womens_college_basketball_pbp/play_by_play_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } #' **Load wehoop women's college basketball team box scores** #' @name load_wbb_team_box NULL #' @title #' **Load cleaned women's college basketball team box scores from the data repo** #' @rdname load_wbb_team_box #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given women's college basketball seasons. (Min: 2006) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wbb_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the play by play data table within the database #' @return Returns a tibble #' @export #' @examples \donttest{ #' try(load_wbb_team_box()) #' } load_wbb_team_box <- function(seasons = most_recent_wbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2006:most_recent_wbb_season() stopifnot(is.numeric(seasons), seasons >= 2006, seasons <= most_recent_wbb_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_womens_college_basketball_team_boxscores/team_box_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } #' **Load wehoop women's college basketball player box scores** #' @name load_wbb_player_box NULL #' @title #' **Load cleaned women's college basketball player box scores from the data repo** #' @rdname load_wbb_player_box #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given women's college basketball seasons. (Min: 2006) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wbb_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the play by play data table within the database #' @return Returns a tibble #' @export #' @examples \donttest{ #' try(load_wbb_player_box()) #' } load_wbb_player_box <- function(seasons = most_recent_wbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2003:most_recent_wbb_season() stopifnot(is.numeric(seasons), seasons >= 2003, seasons <= most_recent_wbb_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_womens_college_basketball_player_boxscores/player_box_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } #' **Load wehoop women's college basketball schedule** #' @name load_wbb_schedule NULL #' @title #' **Load cleaned women's college basketball schedules from the data repo** #' @rdname load_wbb_schedule #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given women's college basketball seasons. (Min: 2002) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wbb_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the play by play data table within the database #' @return Returns a tibble #' @export #' @examples \donttest{ #' try(load_wbb_schedule()) #' } load_wbb_schedule <- function(seasons = most_recent_wbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2002:most_recent_wbb_season() stopifnot(is.numeric(seasons), seasons >= 2002, seasons <= most_recent_wbb_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_womens_college_basketball_schedules/wbb_schedule_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } # load games file load_wbb_games <- function(){ .url <- "https://raw.githubusercontent.com/sportsdataverse/wehoop-data/main/wbb/wbb_games_in_data_repo.csv" dat <- csv_from_url(.url) # close(con) return(dat) } #' **Build/update wehoop WBB play-by-play database** #' @name update_wbb_db NULL #' @title #' **Update or create a wehoop WBB play-by-play database** #' @rdname update_wbb_db #' @description update_wbb_db() updates or creates a database with `wehoop` #' play by play data of all completed and available games since 2002. #' #' @details This function creates and updates a data table with the name `tblname` #' within a SQLite database (other drivers via `db_connection`) located in #' `dbdir` and named `dbname`. #' The data table combines all play by play data for every available game back #' to the 2002 season and adds the most recent completed games as soon as they #' are available for `wehoop`. #' #' The argument `force_rebuild` is of hybrid type. It can rebuild the play #' by play data table either for the whole wehoop era (with `force_rebuild = TRUE`) #' or just for specified seasons (e.g. `force_rebuild = c(2019, 2020)`). #' Please note the following behavior: #' #' - `force_rebuild = TRUE`: The data table with the name `tblname` #' will be removed completely and rebuilt from scratch. This is helpful when #' new columns are added during the Off-Season. #' - `force_rebuild = c(2019, 2020)`: The data table with the name `tblname` #' will be preserved and only rows from the 2019 and 2020 seasons will be #' deleted and re-added. This is intended to be used for ongoing seasons because #' ESPN's data provider can make changes to the underlying data during the week. #' #' #' The parameter `db_connection` is intended for advanced users who want #' to use other DBI drivers, such as MariaDB, Postgres or odbc. Please note that #' the arguments `dbdir` and `dbname` are dropped in case a `db_connection` #' is provided but the argument `tblname` will still be used to write the #' data table into the database. #' #' @param dbdir Directory in which the database is or shall be located #' @param dbname File name of an existing or desired SQLite database within `dbdir` #' @param tblname The name of the play by play data table within the database #' @param force_rebuild Hybrid parameter (logical or numeric) to rebuild parts #' of or the complete play by play data table within the database (please see details for further information) #' @param db_connection A `DBIConnection` object, as returned by #' [DBI::dbConnect()] (please see details for further information) #' @return Logical TRUE/FALSE #' @export update_wbb_db <- function(dbdir = ".", dbname = "wehoop_db", tblname = "wehoop_wbb_pbp", force_rebuild = FALSE, db_connection = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) # rule_header("Update wehoop Play-by-Play Database") if (!is_installed("DBI") | !is_installed("purrr") | (!is_installed("RSQLite") & is.null(db_connection))) { usethis::ui_stop("{my_time()} | Packages {usethis::ui_value('DBI')}, {usethis::ui_value('RSQLite')} and {usethis::ui_value('purrr')} required for database communication. Please install them.") } if (any(force_rebuild == "NEW")) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild = NEW')} is only for internal usage!") } if (!(is.logical(force_rebuild) | is.numeric(force_rebuild))) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild')} has to be either logical or numeric!") } if (!dir.exists(dbdir) & is.null(db_connection)) { usethis::ui_oops("{my_time()} | Directory {usethis::ui_path(dbdir)} doesn't exist yet. Try creating...") dir.create(dbdir) } if (is.null(db_connection)) { connection <- DBI::dbConnect(RSQLite::SQLite(), glue::glue("{dbdir}/{dbname}")) } else { connection <- db_connection } # create db if it doesn't exist or user forces rebuild if (!DBI::dbExistsTable(connection, tblname)) { build_wbb_db(tblname, connection, rebuild = "NEW") } else if (DBI::dbExistsTable(connection, tblname) & all(force_rebuild != FALSE)) { build_wbb_db(tblname, connection, rebuild = force_rebuild) } # get completed games user_message("Checking for missing completed games...", "todo") completed_games <- load_wbb_games() %>% # completed games since 2006, excluding the broken games dplyr::filter(.data$season >= 2004) %>% dplyr::pull(.data$game_id) # function below missing <- get_missing_wbb_games(completed_games, connection, tblname) # rebuild db if number of missing games is too large if (length(missing) > 100) { build_wbb_db(tblname, connection, show_message = FALSE, rebuild = as.numeric(unique(stringr::str_sub(missing, 1, 4)))) missing <- get_missing_wbb_games(completed_games, connection, tblname) } # # if there's missing games, scrape and write to db # if (length(missing) > 0) { # new_pbp <- build_wehoop_pbp(missing, rules = FALSE) # # if (nrow(new_pbp) == 0) { # user_message("Raw data of new games are not yet ready. Please try again in about 10 minutes.", "oops") # } else { # user_message("Appending new data to database...", "todo") # DBI::dbWriteTable(connection, tblname, new_pbp, append = TRUE) # } # } message_completed("Database update completed", in_builder = TRUE) usethis::ui_info("{my_time()} | Path to your db: {usethis::ui_path(DBI::dbGetInfo(connection)$dbname)}") if (is.null(db_connection)) DBI::dbDisconnect(connection) # rule_footer("DONE") } # this is a helper function to build wehoop database from Scratch build_wbb_db <- function(tblname = "wehoop_wbb_pbp", db_conn, rebuild = FALSE, show_message = TRUE) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) valid_seasons <- load_wbb_games() %>% dplyr::filter(.data$season >= 2004) %>% dplyr::group_by(.data$season) %>% dplyr::summarise() %>% dplyr::ungroup() if (all(rebuild == TRUE)) { usethis::ui_todo("{my_time()} | Purging the complete data table {usethis::ui_value(tblname)} in your connected database...") DBI::dbRemoveTable(db_conn, tblname) seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else if (is.numeric(rebuild) & all(rebuild %in% valid_seasons$season)) { string <- paste0(rebuild, collapse = ", ") if (show_message) {usethis::ui_todo("{my_time()} | Purging {string} season(s) from the data table {usethis::ui_value(tblname)} in your connected database...")} DBI::dbExecute(db_conn, glue::glue_sql("DELETE FROM {`tblname`} WHERE season IN ({vals*})", vals = rebuild, .con = db_conn)) seasons <- valid_seasons %>% dplyr::filter(.data$season %in% rebuild) %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of the {string} season(s)...") } else if (all(rebuild == "NEW")) { usethis::ui_info("{my_time()} | Can't find the data table {usethis::ui_value(tblname)} in your database. Will load the play by play data from scratch.") seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else { seasons <- NULL usethis::ui_oops("{my_time()} | At least one invalid value passed to argument {usethis::ui_code('force_rebuild')}. Please try again with valid input.") } if (!is.null(seasons)) { # this function lives in R/utils.R load_wbb_pbp(rev(seasons), dbConnection = db_conn, tablename = tblname) } } # this is a helper function to check a list of completed games # against the games that exist in a database connection get_missing_wbb_games <- function(completed_games, dbConnection, tablename) { db_ids <- dplyr::tbl(dbConnection, tablename) %>% dplyr::select("game_id") %>% dplyr::distinct() %>% dplyr::collect() %>% dplyr::pull("game_id") need_scrape <- completed_games[!completed_games %in% db_ids] usethis::ui_info("{my_time()} | You have {length(db_ids)} games and are missing {length(need_scrape)}.") return(need_scrape) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/load_wbb.R
#' **Load wehoop WNBA play-by-play** #' @name load_wnba_pbp NULL #' @title #' **Load cleaned WNBA play-by-play from the data repo** #' @rdname load_wnba_pbp #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given WNBA seasons. (Min: 2002) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wnba_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the play by play data table within the database #' @return A dataframe with 42 columns #' \describe{ #' \item{shooting_play}{Logical value (TRUE/FALSE) indicating whether the play was a shooting play} #' \item{sequence_number}{Sequence number is supposed to represent a shot-possession, examine the last two numbers to see if there are multiple events that occur within the same shot-possession. A shot-possession is basically any sequence of plays until there is a shot, change in possession, and probably things like technical fouls and the like. So as soon as a shot goes up, a new sequence starts regardless, even if the shooting team retains possession via offensive or deadball rebound. The first portion of the number is usually time related (i.e. the numeric representation of when the sequence started, from a seconds remaining in the period perspective or so)} #' \item{period_display_value}{Long form of period (1st quarter, 2nd Quarter, OT, etc.)} #' \item{period_number}{The numeric period of play in the game } #' \item{home_score}{Home score at the time of the play} #' \item{coordinate_x}{The entire scale is a rectangle of size 25x47, intended as a half-court representation of the basketball court (i.e. on the side of the offense), with each coordinate unit representing a foot. It appears that the basket is roughly represented as the (25, 0) point. This is a nonsensical definition when considering that the basket overhangs the court, with the backboard aligned 48 inches from the baseline, then the center of the hoop being roughly 11 inches from there. This is an idiosyncracy of either sensor placement or software and data entry. Use your best judgement in making your charts, I think you will find that making some translations will be helpful. } #' \item{coordinate_y}{} #' \item{scoring_play}{Logical value (TRUE/FALSE) indicating whether the play was a play on which the offense scored} #' \item{clock_display_value}{Time left within the period} #' \item{team_id}{Unique team identification number for the offensive team} #' \item{type_id}{Unique play type identifcation number} #' \item{type_text}{Play type text description} #' \item{away_score}{Away score at the time of the play} #' \item{id}{Unique play identifcation number} #' \item{text}{Text description of the play} #' \item{score_value}{The points value of the shot taken} #' \item{participants_0_athlete_id}{Unique player identification number } #' \item{participants_1_athlete_id}{Unique player identification number } #' \item{participants_2_athlete_id}{Unique player identification number } #' \item{type_abbreviation}{Play type abbreviation} #' \item{season}{Season of the game} #' \item{season_type}{Season type of the game, 1 is pre-season, 2 is regular season, 3 is post-season, 4 is off-season} #' \item{away_team_id}{Unique away team identification number} #' \item{away_team_name}{Away team name} #' \item{away_team_mascot}{Away team mascot} #' \item{away_team_abbrev}{Text abbreviation for the away team} #' \item{away_team_name_alt}{Alternate versions of the away team abbreviation} #' \item{home_team_id}{Unique home team identification number} #' \item{home_team_name}{home team name} #' \item{home_team_mascot}{home team mascot} #' \item{home_team_abbrev}{Text abbreviation for the home team} #' \item{home_team_name_alt}{Alternate versions of the home team abbreviation} #' \item{home_team_spread}{The game spread with respect to the home team} #' \item{game_spread}{Game spread in (-X Team) format. There are almost none, I would recommend not trusting any of these three columns} #' \item{home_favorite}{Logical (TRUE/FALSE) indicating whether the home team is favored} #' \item{clock_minutes}{Clock minutes split from seconds for developer convenience} #' \item{clock_seconds}{Clock seconds split from minutes for developer convenience} #' \item{half}{Half of the game} #' \item{lag_half}{A lag column on the half} #' \item{lead_half}{A lead column on the half} #' \item{game_play_number}{Game play number} #' \item{game_id}{Unique identifier for the game event} #' } #' @export #' @examples #' \donttest{ #' try(load_wnba_pbp()) #' } load_wnba_pbp <- function(seasons = most_recent_wnba_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2002:most_recent_wnba_season() stopifnot(is.numeric(seasons), seasons >= 2002, seasons <= most_recent_wnba_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_wnba_pbp/play_by_play_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } #' **Load wehoop WNBA team box scores** #' @name load_wnba_team_box NULL #' @title #' **Load cleaned WNBA team box scores from the data repo** #' @rdname load_wnba_team_box #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given WNBA seasons. (Min: 2003) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wnba_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the team box data table within the database #' @return Returns a tibble #' @export #' @examples #' \donttest{ #' try(load_wnba_team_box()) #' } load_wnba_team_box <- function(seasons = most_recent_wnba_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2003:most_recent_wnba_season() stopifnot(is.numeric(seasons), seasons >= 2003, seasons <= most_recent_wnba_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_wnba_team_boxscores/team_box_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") out } #' **Load wehoop WNBA player box scores** #' @name load_wnba_player_box NULL #' @title #' **Load cleaned WNBA player box scores from the data repo** #' @rdname load_wnba_player_box #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given WNBA seasons. (Min: 2002) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wnba_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the player box data table within the database #' @return Returns a tibble #' @export #' @examples #' \donttest{ #' try(load_wnba_player_box()) #' } load_wnba_player_box <- function(seasons = most_recent_wnba_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2002:most_recent_wnba_season() stopifnot(is.numeric(seasons), seasons >= 2002, seasons <= most_recent_wnba_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_wnba_player_boxscores/player_box_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } #' **Load wehoop WNBA schedules** #' @name load_wnba_schedule NULL #' @title #' **Load cleaned WNBA schedules from the data repo** #' @rdname load_wnba_schedule #' @description helper that loads multiple seasons from the data repo either into memory #' or writes it into a db using some forwarded arguments in the dots #' @param seasons A vector of 4-digit years associated with given WNBA seasons. (Min: 2002) #' @param ... Additional arguments passed to an underlying function that writes #' the season data into a database (used by `update_wnba_db()`). #' @param dbConnection A `DBIConnection` object, as returned by [DBI::dbConnect()] #' @param tablename The name of the schedule data table within the database #' @return Returns a tibble #' @export #' @examples #' \donttest{ #' try(load_wnba_schedule()) #' } load_wnba_schedule <- function(seasons = most_recent_wnba_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if (isTRUE(seasons)) seasons <- 2002:most_recent_wnba_season() stopifnot(is.numeric(seasons), seasons >= 2002, seasons <= most_recent_wnba_season()) urls <- paste0("https://github.com/sportsdataverse/sportsdataverse-data/releases/download/espn_wnba_schedules/wnba_schedule_", seasons, ".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") } out } # load games file load_wnba_games <- function(){ .url <- "https://raw.githubusercontent.com/sportsdataverse/wehoop-data/main/wnba/wnba_games_in_data_repo.csv" con <- url(.url) dat <- utils::read.csv(con) # close(con) return(dat) } #' **Build/update wehoop WNBA play-by-play database** #' @name update_wnba_db NULL #' @title #' **Update or create a wehoop WNBA play-by-play database** #' @rdname update_wnba_db #' @description update_wnba_db() updates or creates a database with `wehoop` #' play by play data of all completed and available games since 2002. #' #' @details This function creates and updates a data table with the name `tblname` #' within a SQLite database (other drivers via `db_connection`) located in #' `dbdir` and named `dbname`. #' The data table combines all play by play data for every available game back #' to the 2002 season and adds the most recent completed games as soon as they #' are available for `wehoop`. #' #' The argument `force_rebuild` is of hybrid type. It can rebuild the play #' by play data table either for the whole wehoop era (with `force_rebuild = TRUE`) #' or just for specified seasons (e.g. `force_rebuild = c(2019, 2020)`). #' Please note the following behavior: #' #' - `force_rebuild = TRUE`: The data table with the name `tblname` #' will be removed completely and rebuilt from scratch. This is helpful when #' new columns are added during the Off-Season. #' - `force_rebuild = c(2019, 2020)`: The data table with the name `tblname` #' will be preserved and only rows from the 2019 and 2020 seasons will be #' deleted and re-added. This is intended to be used for ongoing seasons because #' ESPN's data provider can make changes to the underlying data during the week. #' #' #' #' The parameter `db_connection` is intended for advanced users who want #' to use other DBI drivers, such as MariaDB, Postgres or odbc. Please note that #' the arguments `dbdir` and `dbname` are dropped in case a `db_connection` #' is provided but the argument `tblname` will still be used to write the #' data table into the database. #' #' @param dbdir Directory in which the database is or shall be located #' @param dbname File name of an existing or desired SQLite database within `dbdir` #' @param tblname The name of the play by play data table within the database #' @param force_rebuild Hybrid parameter (logical or numeric) to rebuild parts #' of or the complete play by play data table within the database (please see details for further information) #' @param db_connection A `DBIConnection` object, as returned by #' [DBI::dbConnect()] (please see details for further information) #' @return Logical TRUE/FALSE #' @export update_wnba_db <- function(dbdir = ".", dbname = "wehoop_db", tblname = "wehoop_wnba_pbp", force_rebuild = FALSE, db_connection = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) # rule_header("Update wehoop Play-by-Play Database") if (!is_installed("DBI") | !is_installed("purrr") | (!is_installed("RSQLite") & is.null(db_connection))) { usethis::ui_stop("{my_time()} | Packages {usethis::ui_value('DBI')}, {usethis::ui_value('RSQLite')} and {usethis::ui_value('purrr')} required for database communication. Please install them.") } if (any(force_rebuild == "NEW")) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild = NEW')} is only for internal usage!") } if (!(is.logical(force_rebuild) | is.numeric(force_rebuild))) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild')} has to be either logical or numeric!") } if (!dir.exists(dbdir) & is.null(db_connection)) { usethis::ui_oops("{my_time()} | Directory {usethis::ui_path(dbdir)} doesn't exist yet. Try creating...") dir.create(dbdir) } if (is.null(db_connection)) { connection <- DBI::dbConnect(RSQLite::SQLite(), glue::glue("{dbdir}/{dbname}")) } else { connection <- db_connection } # create db if it doesn't exist or user forces rebuild if (!DBI::dbExistsTable(connection, tblname)) { build_wnba_db(tblname, connection, rebuild = "NEW") } else if (DBI::dbExistsTable(connection, tblname) & all(force_rebuild != FALSE)) { build_wnba_db(tblname, connection, rebuild = force_rebuild) } # get completed games user_message("Checking for missing completed games...", "todo") completed_games <- load_wnba_games() %>% # completed games since 2002, excluding the broken games dplyr::filter(.data$season >= 2002) %>% dplyr::pull(.data$game_id) # function below missing <- get_missing_wnba_games(completed_games, connection, tblname) # rebuild db if number of missing games is too large if (length(missing) > 100) { build_wnba_db(tblname, connection, show_message = FALSE, rebuild = as.numeric(unique(stringr::str_sub(missing, 1, 4)))) missing <- get_missing_wnba_games(completed_games, connection, tblname) } # # if there's missing games, scrape and write to db # if (length(missing) > 0) { # new_pbp <- build_wehoop_pbp(missing, rules = FALSE) # # if (nrow(new_pbp) == 0) { # user_message("Raw data of new games are not yet ready. Please try again in about 10 minutes.", "oops") # } else { # user_message("Appending new data to database...", "todo") # DBI::dbWriteTable(connection, tblname, new_pbp, append = TRUE) # } # } message_completed("Database update completed", in_builder = TRUE) usethis::ui_info("{my_time()} | Path to your db: {usethis::ui_path(DBI::dbGetInfo(connection)$dbname)}") if (is.null(db_connection)) DBI::dbDisconnect(connection) # rule_footer("DONE") } # this is a helper function to build wehoop database from Scratch build_wnba_db <- function(tblname = "wehoop_wnba_pbp", db_conn, rebuild = FALSE, show_message = TRUE) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) valid_seasons <- load_wnba_games() %>% dplyr::filter(.data$season >= 2002) %>% dplyr::group_by(.data$season) %>% dplyr::summarise() %>% dplyr::ungroup() if (all(rebuild == TRUE)) { usethis::ui_todo("{my_time()} | Purging the complete data table {usethis::ui_value(tblname)} in your connected database...") DBI::dbRemoveTable(db_conn, tblname) seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else if (is.numeric(rebuild) & all(rebuild %in% valid_seasons$season)) { string <- paste0(rebuild, collapse = ", ") if (show_message) {usethis::ui_todo("{my_time()} | Purging {string} season(s) from the data table {usethis::ui_value(tblname)} in your connected database...")} DBI::dbExecute(db_conn, glue::glue_sql("DELETE FROM {`tblname`} WHERE season IN ({vals*})", vals = rebuild, .con = db_conn)) seasons <- valid_seasons %>% dplyr::filter(.data$season %in% rebuild) %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of the {string} season(s)...") } else if (all(rebuild == "NEW")) { usethis::ui_info("{my_time()} | Can't find the data table {usethis::ui_value(tblname)} in your database. Will load the play by play data from scratch.") seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else { seasons <- NULL usethis::ui_oops("{my_time()} | At least one invalid value passed to argument {usethis::ui_code('force_rebuild')}. Please try again with valid input.") } if (!is.null(seasons)) { # this function lives in R/utils.R load_wnba_pbp(seasons, dbConnection = db_conn, tablename = tblname) } } # this is a helper function to check a list of completed games # against the games that exist in a database connection get_missing_wnba_games <- function(completed_games, dbConnection, tablename) { db_ids <- dplyr::tbl(dbConnection, tablename) %>% dplyr::select("game_id") %>% dplyr::distinct() %>% dplyr::collect() %>% dplyr::pull("game_id") need_scrape <- completed_games[!completed_games %in% db_ids] usethis::ui_info("{my_time()} | You have {length(db_ids)} games and are missing {length(need_scrape)}.") return(need_scrape) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/load_wnba.R
#' Get Women's college basketball NET rankings for the current date from the NCAA website #' #' @author Saiem Gilani #' @return Returns a tibble #' #' |col_name |types | #' |:----------|:---------| #' |rank |integer | #' |previous |integer | #' |school |character | #' |conference |character | #' |record |character | #' |road |character | #' |neutral |character | #' |home |character | #' |non_div_i |character | #' #' @importFrom dplyr %>% as_tibble #' @import rvest #' @export #' @keywords NCAA WBB NET Rankings #' @family NCAA WBB Functions #' @examples #' # Get current NCAA NET rankings #' \donttest{ #' try(ncaa_wbb_NET_rankings()) #' } ncaa_wbb_NET_rankings <- function(){ NET_url <- "https://www.ncaa.com/rankings/basketball-women/d1/ncaa-womens-basketball-net-rankings" tryCatch( expr = { x <- (NET_url %>% xml2::read_html() %>% rvest::html_nodes("table"))[[1]] %>% rvest::html_table(fill = TRUE) %>% dplyr::as_tibble() %>% janitor::clean_names() %>% make_wehoop_data("NCAA WBB NET Rankings Information from NCAA.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no NET rankings available!")) }, warning = function(w) { }, finally = { } ) return(x) } #' @title **Scrape NCAA Women's Baskebtall Teams (Division I, II, and III)** #' @description This function allows the user to obtain NCAA teams by year and division #' @param year The season for which data should be returned, in the form of "YYYY". Years currently available: 2002 onward. #' @param division Division - 1, 2, 3 #' @param ... Additional arguments passed to an underlying function like httr. #' @return A data frame with the following variables #' #' |col_name |types | #' |:-------------|:---------| #' |team_id |character | #' |team_name |character | #' |team_url |character | #' |conference_id |character | #' |conference |character | #' |division |numeric | #' |year |numeric | #' |season_id |character | #' #' @import dplyr #' @import rvest #' @importFrom stringr str_split #' @export #' @details #' ```r #' ncaa_wbb_teams(year = 2023, division = 1) #' ``` ncaa_wbb_teams <- function(year = most_recent_wbb_season(), division = 1, ...) { if (is.null(year)) { cli::cli_abort("Enter valid year as a number (YYYY)") } if (is.null(division)) { cli::cli_abort("Enter valid division as a number: 1, 2, 3") } if (year < 2002) { stop('you must provide a year that is equal to or greater than 2002') } df <- data.frame() headers <- httr::add_headers(.headers = .ncaa_headers()) tryCatch( expr = { url <- paste0("http://stats.ncaa.org/team/inst_team_list?academic_year=", year, "&conf_id=-1", "&division=", division, "&sport_code=WBB") resp <- httr::RETRY("GET", url = {{url}}, headers, httr::timeout(15)) data_read <- resp %>% httr::content(as = "text", encoding = "UTF-8") %>% xml2::read_html() team_urls <- data_read %>% rvest::html_elements("table") %>% rvest::html_elements("a") %>% rvest::html_attr("href") team_names <- data_read %>% rvest::html_elements("table") %>% rvest::html_elements("a") %>% rvest::html_text() conference_names <- ((data_read %>% rvest::html_elements(".level2"))[[4]] %>% rvest::html_elements("a") %>% rvest::html_text())[-1] conference_ids <- (data_read %>% rvest::html_elements(".level2"))[[4]] %>% rvest::html_elements("a") %>% rvest::html_attr("href") %>% stringr::str_extract("javascript:changeConference\\(\\d+\\)") %>% stringr::str_subset("javascript:changeConference\\(\\d+\\)") %>% stringr::str_extract("\\d+") conference_df <- data.frame(conference = conference_names, conference_id = conference_ids) conferences_team_df <- lapply(conference_df$conference_id, function(x){ conf_team_urls <- paste0("http://stats.ncaa.org/team/inst_team_list?academic_year=", year, "&conf_id=", x, "&division=", division, "&sport_code=WBB") resp <- httr::RETRY("GET", url = {{conf_team_urls}}, headers, httr::timeout(15)) team_urls <- resp %>% httr::content(as = "text", encoding = "UTF-8") %>% xml2::read_html() %>% rvest::html_elements("table") %>% rvest::html_elements("a") %>% rvest::html_attr("href") team_names <- resp %>% httr::content(as = "text", encoding = "UTF-8") %>% xml2::read_html() %>% rvest::html_elements("table") %>% rvest::html_elements("a") %>% rvest::html_text() data <- data.frame(team_url = team_urls, team_name = team_names, division = division, year = year, conference_id = x) data <- data %>% dplyr::left_join(conference_df, by = c("conference_id")) Sys.sleep(5) return(data) }) conferences_team_df <- rbindlist_with_attrs(conferences_team_df) conferences_team_df$team_id <- conferences_team_df$team_url %>% stringr::str_extract("(\\d+)\\/(\\d+)", group = 1) conferences_team_df$season_id <- conferences_team_df$team_url %>% stringr::str_extract("(\\d+)\\/(\\d+)", group = 2) df <- as.data.frame(conferences_team_df) df <- df %>% dplyr::select(dplyr::any_of(c( "team_id", "team_name", "team_url", "conference_id", "conference", "division", "year", "season_id"))) %>% make_wehoop_data("NCAA WBB Teams data from stats.ncaa.org", Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments provided")) }, finally = { } ) return(df) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/ncaa_wbb_data.R
.datatable.aware <- TRUE #' Progressively #' #' This function helps add progress-reporting to any function - given function `f()` and progressor `p()`, it will return a new function that calls `f()` and then (on-exiting) will call `p()` after every iteration. #' #' This is inspired by purrr's `safely`, `quietly`, and `possibly` function decorators. #' #' @param f a function to add progressr functionality to. #' @param p a progressor function as created by `progressr::progressor()` #' @keywords Internal #' #' @return a function that does the same as `f` but it calls `p()` after iteration. #' progressively <- function(f, p = NULL){ if (!is.null(p) && !inherits(p, "progressor")) stop("`p` must be a progressor function!") if (is.null(p)) p <- function(...) NULL force(f) function(...){ on.exit(p("loading...")) f(...) } } #' @title #' **Load .csv / .csv.gz file from a remote connection** #' @description #' This is a thin wrapper on data.table::fread #' @param ... passed to data.table::fread #' @keywords Internal #' @importFrom data.table fread csv_from_url <- function(...){ data.table::fread(...) } #' @title #' **Load .rds file from a remote connection** #' @param url a character url #' @keywords Internal #' @return a dataframe as created by [`readRDS()`] #' @importFrom data.table data.table setDT #' @import rvest rds_from_url <- function(url) { con <- url(url) on.exit(close(con)) load <- try(readRDS(con), silent = TRUE) if (inherits(load, "try-error")) { warning(paste0("Failed to readRDS from <", url, ">"), call. = FALSE) return(data.table::data.table()) } data.table::setDT(load) return(load) } # The function `message_completed` to create the green "...completed" message # only exists to hide the option `in_builder` in dots message_completed <- function(x, in_builder = FALSE) { if (!in_builder) { usethis::ui_done("{usethis::ui_field(x)}") } else if (in_builder) { usethis::ui_done(x) } } user_message <- function(x, type) { if (type == "done") { usethis::ui_done("{my_time()} | {x}") } else if (type == "todo") { usethis::ui_todo("{my_time()} | {x}") } else if (type == "info") { usethis::ui_info("{my_time()} | {x}") } else if (type == "oops") { usethis::ui_oops("{my_time()} | {x}") } } # check if a package is installed is_installed <- function(pkg) requireNamespace(pkg, quietly = TRUE) # custom mode function from https://stackoverflow.com/questions/2547402/is-there-a-built-in-function-for-finding-the-mode/8189441 custom_mode <- function(x, na.rm = TRUE) { if (na.rm) { x <- x[!is.na(x)] } ux <- unique(x) return(ux[which.max(tabulate(match(x, ux)))]) } #' @title #' **Most Recent Women's College Basketball Season** #' @export most_recent_wbb_season <- function() { ifelse( as.double(substr(Sys.Date(), 6, 7)) >= 10, as.double(substr(Sys.Date(), 1, 4)) + 1, as.double(substr(Sys.Date(), 1, 4)) ) } #' @title #' **Most Recent WNBA Season** #' @export most_recent_wnba_season <- function() { ifelse( as.double(substr(Sys.Date(), 6, 7)) >= 5, as.double(substr(Sys.Date(), 1, 4)), as.double(substr(Sys.Date(), 1, 4)) - 1 ) } my_time <- function() strftime(Sys.time(), format = "%H:%M:%S") #' Check Status function #' @param res Response from API #' @keywords Internal #' @import rvest #' check_status <- function(res) { x = httr::status_code(res) if (x != 200) stop("The API returned an error", call. = FALSE) } #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL #' @import utils utils::globalVariables(c("where")) # check if a package is installed is_installed <- function(pkg) requireNamespace(pkg, quietly = TRUE) #' @keywords internal "_PACKAGE" #' @importFrom Rcpp getRcppVersion #' @importFrom RcppParallel defaultNumThreads NULL `%c%` <- function(x,y){ ifelse(!is.na(x),x,y) } # Functions for custom class # turn a data.frame into a tibble/wehoop_data make_wehoop_data <- function(df, type, timestamp){ out <- df %>% tidyr::as_tibble() class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") attr(out,"wehoop_timestamp") <- timestamp attr(out,"wehoop_type") <- type return(out) } #' @export #' @noRd print.wehoop_data <- function(x,...) { cli::cli_rule(left = "{attr(x,'wehoop_type')}",right = "{.emph wehoop {utils::packageVersion('wehoop')}}") if (!is.null(attr(x,'wehoop_timestamp'))) { cli::cli_alert_info( "Data updated: {.field {format(attr(x,'wehoop_timestamp'), tz = Sys.timezone(), usetz = TRUE)}}" ) } NextMethod(print,x) invisible(x) } # rbindlist but maintain attributes of last file rbindlist_with_attrs <- function(dflist){ wehoop_timestamp <- attr(dflist[[length(dflist)]], "wehoop_timestamp") wehoop_type <- attr(dflist[[length(dflist)]], "wehoop_type") out <- data.table::rbindlist(dflist, use.names = TRUE, fill = TRUE) attr(out,"wehoop_timestamp") <- wehoop_timestamp attr(out,"wehoop_type") <- wehoop_type class(out) <- c("wehoop_data","tbl_df","tbl","data.table","data.frame") out }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/utils.R
.wnba_headers <- function(url = "https://stats.wnba.com/stats/leaguegamelog?Counter=1000&Season=2019-20&Direction=DESC&LeagueID=00&PlayerOrTeam=P&SeasonType=Regular%20Season&Sorter=DATE", params = list(), ..., origin = "https://stats.wnba.com", referer="https://www.wnba.com/") { headers <- c( `Host` = 'stats.wnba.com', `User-Agent` = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36', `Accept` = 'application/json, text/plain, */*', `Accept-Language` = 'en-US,en;q=0.5', `Accept-Encoding` = 'gzip, deflate, br', `x-nba-stats-origin` = 'stats', `x-nba-stats-token` = 'true', `Connection` = 'keep-alive', `Origin` = origin, `Referer` = referer, `Pragma` = 'no-cache', `Cache-Control` = 'no-cache' ) dots <- rlang::dots_list(..., .named = TRUE) proxy <- dots$proxy if (length(params) >= 1) { res <- httr::RETRY("GET", url, query = params, ..., httr::add_headers(.headers = headers)) json <- res$content %>% rawToChar() %>% jsonlite::fromJSON(simplifyVector = T) } else { res <- rvest::html_session(url, ..., httr::add_headers(.headers = headers)) json <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() } return(json) } #' @title #' **Retry http request with proxy** #' @description #' This is a thin wrapper on httr::RETRY #' @param url Request url #' @param params list of params #' @param origin Origin url #' @param referer Referer url #' @param ... passed to httr::RETRY #' @keywords internal #' @import rvest request_with_proxy <- function(url, params = list(), origin = "https://stats.wnba.com", referer="https://www.wnba.com/", ...){ dots <- rlang::dots_list(..., .named = TRUE) proxy <- dots$proxy headers <- dots$headers headers <- c( `Host` = 'stats.wnba.com', `User-Agent` = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0', `Accept` = 'application/json, text/plain, */*', `Accept-Language` = 'en-US,en;q=0.5', `Accept-Encoding` = 'gzip, deflate, br', `x-nba-stats-origin` = 'stats', `x-nba-stats-token` = 'true', `Connection` = 'keep-alive', `Referer` = "https://www.wnba.com/", `Pragma` = 'no-cache', `Cache-Control` = 'no-cache' ) if (length(params) >= 1) { url <- httr::modify_url({{url}}, query = params) res <- rvest::session(url = url, ..., httr::add_headers(.headers = headers), httr::timeout(60)) json <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() } else { res <- rvest::session(url = {{url}}, ..., httr::add_headers(.headers = headers), httr::timeout(60)) json <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() } return(json) } wnba_live_endpoint <- function(endpoint){ base_url = glue::glue('https://cdn.wnba.com/static/json/liveData/{endpoint}') return(base_url) } wnba_endpoint <- function(endpoint){ all_endpoints = c( 'alltimeleadersgrids', 'assistleaders', 'assisttracker', 'boxscoreadvancedv2', 'boxscoredefensive', 'boxscorefourfactorsv2', 'boxscorematchups', 'boxscoremiscv2', 'boxscoreplayertrackv2', 'boxscorescoringv2', 'boxscoresimilarityscore', 'boxscoresummaryv2', 'boxscoretraditionalv2', 'boxscoreusagev2', 'commonallplayers', 'commonplayerinfo', 'commonplayoffseries', 'commonteamroster', 'commonteamyears', 'cumestatsplayer', 'cumestatsplayergames', 'cumestatsteam', 'cumestatsteamgames', 'defensehub', 'draftboard', 'draftcombinedrillresults', 'draftcombinenonstationaryshooting', 'draftcombineplayeranthro', 'draftcombinespotshooting', 'draftcombinestats', 'drafthistory', 'fantasywidget', 'franchisehistory', 'franchiseleaders', 'franchiseplayers', 'gamerotation', 'glalumboxscoresimilarityscore', 'homepageleaders', 'homepagev2', 'infographicfanduelplayer', 'leaderstiles', 'leaguedashlineups', 'leaguedashplayerbiostats', 'leaguedashplayerclutch', 'leaguedashplayerptshot', 'leaguedashplayershotlocations', 'leaguedashplayerstats', 'leaguedashptdefend', 'leaguedashptstats', 'leaguedashptteamdefend', 'leaguedashteamclutch', 'leaguedashoppptshot', 'leaguedashteamptshot', 'leaguedashteamshotlocations', 'leaguedashteamstats', 'leaguegamefinder', 'leaguegamelog', 'leagueleaders', 'leaguelineupviz', 'leagueplayerondetails', 'leagueseasonmatchups', 'leaguestandings', 'leaguestandingsv3', 'matchupsrollup', 'playbyplay', 'playbyplayv2', 'playerawards', 'playercareerbycollege', 'playercareerbycollegerollup', 'playercareerstats', 'playercompare', 'playerdashptpass', 'playerdashptreb', 'playerdashptshotdefend', 'playerdashptshots', 'playerdashboardbyclutch', 'playerdashboardbygamesplits', 'playerdashboardbygeneralsplits', 'playerdashboardbylastngames', 'playerdashboardbyopponent', 'playerdashboardbyshootingsplits', 'playerdashboardbyteamperformance', 'playerdashboardbyyearoveryear', 'playerestimatedmetrics', 'playerfantasyprofile', 'playerfantasyprofilebargraph', 'playergamelog', 'playergamelogs', 'playergamestreakfinder', 'playernextngames', 'playerprofilev2', 'playervsplayer', 'playoffpicture', 'scoreboard', 'scoreboardv2', 'shotchartdetail', 'shotchartleaguewide', 'shotchartlineupdetail', 'synergyplaytypes', 'teamandplayersvsplayers', 'teamdashlineups', 'teamdashptpass', 'teamdashptreb', 'teamdashptshots', 'teamdashboardbyclutch', 'teamdashboardbygamesplits', 'teamdashboardbygeneralsplits', 'teamdashboardbylastngames', 'teamdashboardbyopponent', 'teamdashboardbyshootingsplits', 'teamdashboardbyteamperformance', 'teamdashboardbyyearoveryear', 'teamdetails', 'teamestimatedmetrics', 'teamgamelog', 'teamgamelogs', 'teamgamestreakfinder', 'teamhistoricalleaders', 'teaminfocommon', 'teamplayerdashboard', 'teamplayeronoffdetails', 'teamplayeronoffsummary', 'teamvsplayer', 'teamyearbyyearstats', 'videodetails', 'videoevents', 'videostatus', 'winprobabilitypbp' ) base_url = glue::glue('https://stats.wnba.com/stats/{endpoint}') return(base_url) } wnba_stats_map_result_sets <- function(resp) { if ("resultSets" %in% names(resp)) { df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% dplyr::as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name return(df_list) } else { df_list <- purrr::map(1:length(resp$resultSet$name), function(x){ data <- resp$resultSet$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% dplyr::as_tibble() json_names <- resp$resultSet$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSet$name return(df_list) } } pad_id <- function(id = 1012100001) { zeros <- 10 - nchar(id) if (zeros == 0) { return(id) } start <- rep("0", times = zeros) %>% stringr::str_c(collapse = "") glue("{start}{id}") %>% as.character() } .ncaa_headers <- function(url){ headers <- c( `Host` = 'stats.ncaa.org', `User-Agent` = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36', `Accept` = 'application/json, text/html, text/plain, */*', `Accept-Language` = 'en-US,en;q=0.5', `Accept-Encoding` = 'gzip, deflate, br', `Pragma` = 'no-cache', `Cache-Control` = 'no-cache' ) return(headers) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/utils_wnba_stats.R
#' @keywords internal "_PACKAGE" # The following block is used by usethis to automatically manage # roxygen namespace tags. Modify with care! ## usethis namespace: start #' @importFrom janitor clean_names #' @importFrom stringr str_c ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wehoop-package.R
#' **Get WNBA Data API Play-by-Play** #' @name wnba_data_pbp NULL #' @title #' **Get WNBA Data API Play-by-Play** #' @rdname wnba_data_pbp #' @author Saiem Gilani #' @param game_id Game ID - 10 digits, i.e. "0021900001" #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a tibble #' #' |col_name |types | #' |:-----------------|:---------| #' |game_id |character | #' |league |character | #' |period |integer | #' |event_num |integer | #' |clock |character | #' |description |character | #' |locX |integer | #' |locY |integer | #' |opt1 |integer | #' |opt2 |integer | #' |event_action_type |integer | #' |event_type |integer | #' |team_id |integer | #' |offense_team_id |integer | #' |player1_id |integer | #' |player2_id |integer | #' |player3_id |integer | #' |home_score |integer | #' |away_score |integer | #' |order |integer | #' #' Event Message Types (event_type): #' #' 1 -> MAKE #' #' 2 -> MISS #' #' 3 -> FreeThrow #' #' 4 -> Rebound #' #' 5 -> Turnover #' #' 6 -> Foul #' #' 7 -> Violation #' #' 8 -> Substitution #' #' 9 -> Timeout #' #' 10 -> JumpBall #' #' 11 -> Ejection #' #' 12 -> StartOfPeriod #' #' 13 -> EndOfPeriod #' #' 14 -> Empty #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr select mutate rename case_when #' @importFrom tidyr everything #' @import rvest #' @export #' @family WNBA PBP Functions #' @details #' ```r #' wnba_data_pbp(game_id = "1022200034") #' ``` wnba_data_pbp <- function(game_id = "1022200034", ...){ league_id <- substr(game_id, 1, 2) season_id <- substr(game_id, 4, 5) season <- ifelse(substr(season_id,1,1) == "9", paste0('19', season_id), paste0('20', season_id)) league <- dplyr::case_when( substr(game_id, 1, 2) == '00' ~ 'nba', substr(game_id, 1, 2) == '10' ~ 'wnba', substr(game_id, 1, 2) == '20' ~ 'dleague', TRUE ~ 'NBA' ) full_url <- glue::glue("https://data.{league}.com/data/10s/v2015/json/mobile_teams/{league}/{season}/scores/pbp/{game_id}_full_pbp.json") tryCatch( expr = { res <- httr::RETRY("GET", full_url, ...) # Check the result check_status(res) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") data <- resp %>% jsonlite::fromJSON() %>% purrr::pluck("g") plays <- data %>% purrr::pluck("pd") %>% jsonlite::toJSON() %>% jsonlite::fromJSON(flatten = TRUE) plays_df <- data.frame() plays_df <- purrr::map_df(plays[[1]],function(x){ plays_df <- plays[[2]][[x]] %>% dplyr::mutate(period = x) %>% dplyr::select("period", tidyr::everything()) }) plays_df <- plays_df %>% dplyr::select(dplyr::any_of(c( "period" = "period", "event_num" = "evt", "clock" = "cl", "description" = "de", "locX" = "locX", "locY" = "locY", "opt1" = "opt1", "opt2" = "opt2", "event_action_type" = "mtype", "event_type" = "etype", "team_id" = "tid", "offense_team_id" = "oftid", "player1_id" = "pid", "player2_id" = "epid", "player3_id" = "opid", "home_score" = "hs", "away_score" = "vs", "order" = "ord"))) %>% dplyr::mutate( player2_id = as.integer(.data$player2_id), player3_id = as.integer(.data$player3_id), game_id = game_id, league = dplyr::case_when( substr(.data$game_id, 1, 2) == '00' ~ 'NBA', substr(.data$game_id, 1, 2) == '10' ~ 'WNBA', substr(.data$game_id, 1, 2) == '20' ~ 'G-League', TRUE ~ 'NBA')) %>% dplyr::select("game_id", "league", tidyr::everything()) %>% make_wehoop_data("WNBA Play-by-Play Information from data.WNBA.com",Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(plays_df) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_data_pbp.R
#' **Get WNBA Stats API Boxscore Traditional V2** #' @name wnba_boxscoretraditionalv2 NULL #' @title #' **Get WNBA Stats API Boxscore Traditional V2** #' @rdname wnba_boxscoretraditionalv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: PlayerStats, TeamStarterBenchStats, TeamStats #' #' **PlayerStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TO |character | #' |PF |character | #' |PTS |character | #' |PLUS_MINUS |character | #' #' **TeamStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TO |character | #' |PF |character | #' |PTS |character | #' |PLUS_MINUS |character | #' #' **TeamStarterBenchStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |STARTERS_BENCH |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TO |character | #' |PF |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscoretraditionalv2(game_id = "1022200034") #' ``` wnba_boxscoretraditionalv2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoretraditionalv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no traditional boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Advanced V2** #' @name wnba_boxscoreadvancedv2 NULL #' @title #' **Get WNBA Stats API Boxscore Advanced V2** #' @rdname wnba_boxscoreadvancedv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: PlayerStats, TeamStats #' #' **PlayerStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |E_OFF_RATING |character | #' |OFF_RATING |character | #' |E_DEF_RATING |character | #' |DEF_RATING |character | #' |E_NET_RATING |character | #' |NET_RATING |character | #' |AST_PCT |character | #' |AST_TOV |character | #' |AST_RATIO |character | #' |OREB_PCT |character | #' |DREB_PCT |character | #' |REB_PCT |character | #' |TM_TOV_PCT |character | #' |EFG_PCT |character | #' |TS_PCT |character | #' |USG_PCT |character | #' |E_USG_PCT |character | #' |E_PACE |character | #' |PACE |character | #' |PACE_PER40 |character | #' |POSS |character | #' |PIE |character | #' #' **TeamStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |E_OFF_RATING |character | #' |OFF_RATING |character | #' |E_DEF_RATING |character | #' |DEF_RATING |character | #' |E_NET_RATING |character | #' |NET_RATING |character | #' |AST_PCT |character | #' |AST_TOV |character | #' |AST_RATIO |character | #' |OREB_PCT |character | #' |DREB_PCT |character | #' |REB_PCT |character | #' |E_TM_TOV_PCT |character | #' |TM_TOV_PCT |character | #' |EFG_PCT |character | #' |TS_PCT |character | #' |USG_PCT |character | #' |E_USG_PCT |character | #' |E_PACE |character | #' |PACE |character | #' |PACE_PER40 |character | #' |POSS |character | #' |PIE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscoreadvancedv2(game_id = "1022200034") #' ``` wnba_boxscoreadvancedv2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoreadvancedv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no advanced boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Four Factors V2** #' @name wnba_boxscorefourfactorsv2 NULL #' @title #' **Get WNBA Stats API Boxscore Four Factors V2** #' @rdname wnba_boxscorefourfactorsv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: sqlPlayersFourFactors, sqlTeamFourFactors #' #' **sqlPlayersFourFactors** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |EFG_PCT |character | #' |FTA_RATE |character | #' |TM_TOV_PCT |character | #' |OREB_PCT |character | #' |OPP_EFG_PCT |character | #' |OPP_FTA_RATE |character | #' |OPP_TOV_PCT |character | #' |OPP_OREB_PCT |character | #' #' **sqlTeamsFourFactors** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |EFG_PCT |character | #' |FTA_RATE |character | #' |TM_TOV_PCT |character | #' |OREB_PCT |character | #' |OPP_EFG_PCT |character | #' |OPP_FTA_RATE |character | #' |OPP_TOV_PCT |character | #' |OPP_OREB_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscorefourfactorsv2(game_id = "1022200034") #' ``` wnba_boxscorefourfactorsv2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscorefourfactorsv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no four factors boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Misc V2** #' @name wnba_boxscoremiscv2 NULL #' @title #' **Get WNBA Stats API Boxscore Misc V2** #' @rdname wnba_boxscoremiscv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: sqlPlayersMisc, sqlTeamsMisc #' #' **sqlPlayersMisc** #' #' #' |col_name |types | #' |:------------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |PTS_OFF_TOV |character | #' |PTS_2ND_CHANCE |character | #' |PTS_FB |character | #' |PTS_PAINT |character | #' |OPP_PTS_OFF_TOV |character | #' |OPP_PTS_2ND_CHANCE |character | #' |OPP_PTS_FB |character | #' |OPP_PTS_PAINT |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' #' **sqlTeamsMisc** #' #' #' |col_name |types | #' |:------------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |PTS_OFF_TOV |character | #' |PTS_2ND_CHANCE |character | #' |PTS_FB |character | #' |PTS_PAINT |character | #' |OPP_PTS_OFF_TOV |character | #' |OPP_PTS_2ND_CHANCE |character | #' |OPP_PTS_FB |character | #' |OPP_PTS_PAINT |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscoremiscv2(game_id = "1022200034") #' ``` wnba_boxscoremiscv2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoremiscv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no miscellaneous boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Scoring V2** #' @name wnba_boxscorescoringv2 NULL #' @title #' **Get WNBA Stats API Boxscore Scoring V2** #' @rdname wnba_boxscorescoringv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: sqlPlayersScoring, sqlTeamsScoring #' #' **sqlPlayersScoring** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |PCT_FGA_2PT |character | #' |PCT_FGA_3PT |character | #' |PCT_PTS_2PT |character | #' |PCT_PTS_2PT_MR |character | #' |PCT_PTS_3PT |character | #' |PCT_PTS_FB |character | #' |PCT_PTS_FT |character | #' |PCT_PTS_OFF_TOV |character | #' |PCT_PTS_PAINT |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' #' **sqlTeamsScoring** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |PCT_FGA_2PT |character | #' |PCT_FGA_3PT |character | #' |PCT_PTS_2PT |character | #' |PCT_PTS_2PT_MR |character | #' |PCT_PTS_3PT |character | #' |PCT_PTS_FB |character | #' |PCT_PTS_FT |character | #' |PCT_PTS_OFF_TOV |character | #' |PCT_PTS_PAINT |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscorescoringv2(game_id = "1022200034") #' ``` wnba_boxscorescoringv2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscorescoringv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoring boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Usage V2** #' @name wnba_boxscoreusagev2 NULL #' @title #' **Get WNBA Stats API Boxscore Usage V2** #' @rdname wnba_boxscoreusagev2 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: sqlPlayersUsage, sqlTeamsUsage #' #' **sqlPlayersUsage** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |USG_PCT |character | #' |PCT_FGM |character | #' |PCT_FGA |character | #' |PCT_FG3M |character | #' |PCT_FG3A |character | #' |PCT_FTM |character | #' |PCT_FTA |character | #' |PCT_OREB |character | #' |PCT_DREB |character | #' |PCT_REB |character | #' |PCT_AST |character | #' |PCT_TOV |character | #' |PCT_STL |character | #' |PCT_BLK |character | #' |PCT_BLKA |character | #' |PCT_PF |character | #' |PCT_PFD |character | #' |PCT_PTS |character | #' #' **sqlTeamsUsage** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |USG_PCT |character | #' |PCT_FGM |character | #' |PCT_FGA |character | #' |PCT_FG3M |character | #' |PCT_FG3A |character | #' |PCT_FTM |character | #' |PCT_FTA |character | #' |PCT_OREB |character | #' |PCT_DREB |character | #' |PCT_REB |character | #' |PCT_AST |character | #' |PCT_TOV |character | #' |PCT_STL |character | #' |PCT_BLK |character | #' |PCT_BLKA |character | #' |PCT_PF |character | #' |PCT_PFD |character | #' |PCT_PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscoreusagev2(game_id = "1022200034") #' ``` wnba_boxscoreusagev2 <- function( game_id, start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoreusagev2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no usage boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Summary V2** #' @name wnba_boxscoresummaryv2 NULL #' @title #' **Get WNBA Stats API Boxscore Summary V2** #' @rdname wnba_boxscoresummaryv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: AvailableVideo, GameInfo, GameSummary, #' InactivePlayers, LastMeeting, LineScore, Officials, OtherStats, SeasonSeries #' #' **GameSummary** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |GAME_STATUS_ID |character | #' |GAME_STATUS_TEXT |character | #' |GAMECODE |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |SEASON |character | #' |LIVE_PERIOD |character | #' |LIVE_PC_TIME |character | #' |NATL_TV_BROADCASTER_ABBREVIATION |character | #' |LIVE_PERIOD_TIME_BCAST |character | #' |WH_STATUS |character | #' #' **OtherStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PTS_PAINT |character | #' |PTS_2ND_CHANCE |character | #' |PTS_FB |character | #' |LARGEST_LEAD |character | #' |LEAD_CHANGES |character | #' |TIMES_TIED |character | #' |TEAM_TURNOVERS |character | #' |TOTAL_TURNOVERS |character | #' |TEAM_REBOUNDS |character | #' |PTS_OFF_TO |character | #' #' **Officials** #' #' #' |col_name |types | #' |:-----------|:---------| #' |OFFICIAL_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |JERSEY_NUM |character | #' #' **InactivePlayers** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |JERSEY_NUM |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' #' **GameInfo** #' #' #' |col_name |types | #' |:----------|:---------| #' |GAME_DATE |character | #' |ATTENDANCE |character | #' |GAME_TIME |character | #' #' **LineScore** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY_NAME |character | #' |TEAM_NICKNAME |character | #' |TEAM_WINS_LOSSES |character | #' |PTS_QTR1 |character | #' |PTS_QTR2 |character | #' |PTS_QTR3 |character | #' |PTS_QTR4 |character | #' |PTS_OT1 |character | #' |PTS_OT2 |character | #' |PTS_OT3 |character | #' |PTS_OT4 |character | #' |PTS_OT5 |character | #' |PTS_OT6 |character | #' |PTS_OT7 |character | #' |PTS_OT8 |character | #' |PTS_OT9 |character | #' |PTS_OT10 |character | #' |PTS |character | #' #' **LastMeeting** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_ID |character | #' |LAST_GAME_ID |character | #' |LAST_GAME_DATE_EST |character | #' |LAST_GAME_HOME_TEAM_ID |character | #' |LAST_GAME_HOME_TEAM_CITY |character | #' |LAST_GAME_HOME_TEAM_NAME |character | #' |LAST_GAME_HOME_TEAM_ABBREVIATION |character | #' |LAST_GAME_HOME_TEAM_POINTS |character | #' |LAST_GAME_VISITOR_TEAM_ID |character | #' |LAST_GAME_VISITOR_TEAM_CITY |character | #' |LAST_GAME_VISITOR_TEAM_NAME |character | #' |LAST_GAME_VISITOR_TEAM_CITY1 |character | #' |LAST_GAME_VISITOR_TEAM_POINTS |character | #' #' **SeasonSeries** #' #' #' |col_name |types | #' |:----------------|:---------| #' |GAME_ID |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |GAME_DATE_EST |character | #' |HOME_TEAM_WINS |character | #' |HOME_TEAM_LOSSES |character | #' |SERIES_LEADER |character | #' #' **AvailableVideo** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |GAME_ID |character | #' |VIDEO_AVAILABLE_FLAG |character | #' |PT_AVAILABLE |character | #' |PT_XYZ_AVAILABLE |character | #' |WH_STATUS |character | #' |HUSTLE_STATUS |character | #' |HISTORICAL_STATUS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @details #' ```r #' wnba_boxscoresummaryv2(game_id = "1022200034") #' ``` wnba_boxscoresummaryv2 <- function( game_id, ...){ version <- "boxscoresummaryv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = pad_id(game_id) ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no summary boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Player Tracking V2** #' @name wnba_boxscoreplayertrackv2 NULL #' @title #' **Get WNBA Stats API Boxscore Player Tracking V2** #' @rdname wnba_boxscoreplayertrackv2 #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: PlayerStats, TeamStats #' #' **PlayerStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MIN |character | #' |SPD |character | #' |DIST |character | #' |ORBC |character | #' |DRBC |character | #' |RBC |character | #' |TCHS |character | #' |SAST |character | #' |FTAST |character | #' |PASS |character | #' |AST |character | #' |CFGM |character | #' |CFGA |character | #' |CFG_PCT |character | #' |UFGM |character | #' |UFGA |character | #' |UFG_PCT |character | #' |FG_PCT |character | #' |DFGM |character | #' |DFGA |character | #' |DFG_PCT |character | #' #' **TeamStats** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MIN |character | #' |DIST |character | #' |ORBC |character | #' |DRBC |character | #' |RBC |character | #' |TCHS |character | #' |SAST |character | #' |FTAST |character | #' |PASS |character | #' |AST |character | #' |CFGM |character | #' |CFGA |character | #' |CFG_PCT |character | #' |UFGM |character | #' |UFGA |character | #' |UFG_PCT |character | #' |FG_PCT |character | #' |DFGM |character | #' |DFGA |character | #' |DFG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @family WNBA Player Tracking Functions #' @details #' ```r #' wnba_boxscoreplayertrackv2(game_id = "1022200034") #' ``` wnba_boxscoreplayertrackv2 <- function( game_id, ...){ version <- "boxscoreplayertrackv2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = pad_id(game_id) ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player tracking boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Hustle Stats Boxscore** #' @name wnba_hustlestatsboxscore NULL #' @title #' **Get WNBA Stats API Hustle Stats Boxscore** #' @rdname wnba_hustlestatsboxscore #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: HustleStatsAvailable, PlayerStats, TeamStats #' #' **HustleStatsAvailable** #' #' #' |col_name |types | #' |:-------------|:---------| #' |GAME_ID |character | #' |HUSTLE_STATUS |character | #' #' **PlayerStats** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |START_POSITION |character | #' |COMMENT |character | #' |MINUTES |character | #' |PTS |character | #' |CONTESTED_SHOTS |character | #' |CONTESTED_SHOTS_2PT |character | #' |CONTESTED_SHOTS_3PT |character | #' |DEFLECTIONS |character | #' |CHARGES_DRAWN |character | #' |SCREEN_ASSISTS |character | #' |SCREEN_AST_PTS |character | #' |OFF_LOOSE_BALLS_RECOVERED |character | #' |DEF_LOOSE_BALLS_RECOVERED |character | #' |LOOSE_BALLS_RECOVERED |character | #' |OFF_BOXOUTS |character | #' |DEF_BOXOUTS |character | #' |BOX_OUT_PLAYER_TEAM_REBS |character | #' |BOX_OUT_PLAYER_REBS |character | #' |BOX_OUTS |character | #' #' **TeamStats** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY |character | #' |MINUTES |character | #' |PTS |character | #' |CONTESTED_SHOTS |character | #' |CONTESTED_SHOTS_2PT |character | #' |CONTESTED_SHOTS_3PT |character | #' |DEFLECTIONS |character | #' |CHARGES_DRAWN |character | #' |SCREEN_ASSISTS |character | #' |SCREEN_AST_PTS |character | #' |OFF_LOOSE_BALLS_RECOVERED |character | #' |DEF_LOOSE_BALLS_RECOVERED |character | #' |LOOSE_BALLS_RECOVERED |character | #' |OFF_BOXOUTS |character | #' |DEF_BOXOUTS |character | #' |BOX_OUT_PLAYER_TEAM_REBS |character | #' |BOX_OUT_PLAYER_REBS |character | #' |BOX_OUTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @family WNBA Hustle Functions #' @details #' ```r #' wnba_hustlestatsboxscore(game_id = "1022200034") #' ``` wnba_hustlestatsboxscore <- function( game_id, ...){ version <- "hustlestatsboxscore" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = pad_id(game_id) ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no hustle stats boxscore data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_boxscore.R
#' **Get WNBA Stats API Boxscore Traditional V3** #' @name wnba_boxscoretraditionalv3 NULL #' @title #' **Get WNBA Stats API Boxscore Traditional V3** #' @rdname wnba_boxscoretraditionalv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: #' home_team_player_traditional, away_team_player_traditional, home_team_totals_traditional, #' away_team_totals_traditional, home_team_starters_totals, away_team_starters_totals, #' home_team_bench_totals, away_team_bench_totals #' #' **home_team_player_traditional** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' |plus_minus_points |numeric | #' #' **away_team_player_traditional** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' |plus_minus_points |numeric | #' #' **home_team_totals_traditional** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' |plus_minus_points |numeric | #' #' **away_team_totals_traditional** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' |plus_minus_points |numeric | #' #' **home_team_starters_totals** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' #' **away_team_starters_totals** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' #' **home_team_bench_totals** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' #' **away_team_bench_totals** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |field_goals_made |integer | #' |field_goals_attempted |integer | #' |field_goals_percentage |numeric | #' |three_pointers_made |integer | #' |three_pointers_attempted |integer | #' |three_pointers_percentage |numeric | #' |free_throws_made |integer | #' |free_throws_attempted |integer | #' |free_throws_percentage |numeric | #' |rebounds_offensive |integer | #' |rebounds_defensive |integer | #' |rebounds_total |integer | #' |assists |integer | #' |steals |integer | #' |blocks |integer | #' |turnovers |integer | #' |fouls_personal |integer | #' |points |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscoretraditionalv3(game_id = "1022200034") #' ``` wnba_boxscoretraditionalv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoretraditionalv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScoreTraditional") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_starters <- home_team_data %>% purrr::pluck("starters") %>% data.frame() home_team_bench <- home_team_data %>% purrr::pluck("bench") %>% data.frame() home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_starters <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_starters) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Starters Boxscore Information from WNBA.com", Sys.time()) home_team_bench <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_bench) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Bench Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_starters <- away_team_data %>% purrr::pluck("starters") %>% data.frame() away_team_bench <- away_team_data %>% purrr::pluck("bench") %>% data.frame() away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_starters <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_starters) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Starters Boxscore Information from WNBA.com", Sys.time()) away_team_bench <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_bench) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Bench Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals), list(home_team_starters), list(away_team_starters), list(home_team_bench), list(away_team_bench) ) names(df_list) <- c( "home_team_player_traditional", "away_team_player_traditional", "home_team_totals_traditional", "away_team_totals_traditional", "home_team_starters_totals", "away_team_starters_totals", "home_team_bench_totals", "away_team_bench_totals" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no traditional boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Advanced V3** #' @name wnba_boxscoreadvancedv3 NULL #' @title #' **Get WNBA Stats API Boxscore Advanced V3** #' @rdname wnba_boxscoreadvancedv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: home_team_player_advanced, away_team_player_advanced, #' home_team_totals_advanced, away_team_totals_advanced #' #' **home_team_player_advanced** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |estimated_offensive_rating |numeric | #' |offensive_rating |numeric | #' |estimated_defensive_rating |numeric | #' |defensive_rating |numeric | #' |estimated_net_rating |numeric | #' |net_rating |numeric | #' |assist_percentage |numeric | #' |assist_to_turnover |numeric | #' |assist_ratio |numeric | #' |offensive_rebound_percentage |numeric | #' |defensive_rebound_percentage |numeric | #' |rebound_percentage |numeric | #' |turnover_ratio |numeric | #' |effective_field_goal_percentage |numeric | #' |true_shooting_percentage |numeric | #' |usage_percentage |numeric | #' |estimated_usage_percentage |numeric | #' |estimated_pace |numeric | #' |pace |numeric | #' |pace_per40 |numeric | #' |possessions |numeric | #' |pie |numeric | #' #' **away_team_player_advanced** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |estimated_offensive_rating |numeric | #' |offensive_rating |numeric | #' |estimated_defensive_rating |numeric | #' |defensive_rating |numeric | #' |estimated_net_rating |numeric | #' |net_rating |numeric | #' |assist_percentage |numeric | #' |assist_to_turnover |numeric | #' |assist_ratio |numeric | #' |offensive_rebound_percentage |numeric | #' |defensive_rebound_percentage |numeric | #' |rebound_percentage |numeric | #' |turnover_ratio |numeric | #' |effective_field_goal_percentage |numeric | #' |true_shooting_percentage |numeric | #' |usage_percentage |numeric | #' |estimated_usage_percentage |numeric | #' |estimated_pace |numeric | #' |pace |numeric | #' |pace_per40 |numeric | #' |possessions |numeric | #' |pie |numeric | #' #' **home_team_totals_advanced** #' #' #' |col_name |types | #' |:----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |estimated_offensive_rating |numeric | #' |offensive_rating |numeric | #' |estimated_defensive_rating |numeric | #' |defensive_rating |numeric | #' |estimated_net_rating |numeric | #' |net_rating |numeric | #' |assist_percentage |numeric | #' |assist_to_turnover |numeric | #' |assist_ratio |numeric | #' |offensive_rebound_percentage |numeric | #' |defensive_rebound_percentage |numeric | #' |rebound_percentage |numeric | #' |estimated_team_turnover_percentage |numeric | #' |turnover_ratio |numeric | #' |effective_field_goal_percentage |numeric | #' |true_shooting_percentage |numeric | #' |usage_percentage |numeric | #' |estimated_usage_percentage |numeric | #' |estimated_pace |numeric | #' |pace |numeric | #' |pace_per40 |numeric | #' |possessions |numeric | #' |pie |numeric | #' #' **away_team_totals_advanced** #' #' #' |col_name |types | #' |:----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |estimated_offensive_rating |numeric | #' |offensive_rating |numeric | #' |estimated_defensive_rating |numeric | #' |defensive_rating |numeric | #' |estimated_net_rating |numeric | #' |net_rating |numeric | #' |assist_percentage |numeric | #' |assist_to_turnover |numeric | #' |assist_ratio |numeric | #' |offensive_rebound_percentage |numeric | #' |defensive_rebound_percentage |numeric | #' |rebound_percentage |numeric | #' |estimated_team_turnover_percentage |numeric | #' |turnover_ratio |numeric | #' |effective_field_goal_percentage |numeric | #' |true_shooting_percentage |numeric | #' |usage_percentage |numeric | #' |estimated_usage_percentage |numeric | #' |estimated_pace |numeric | #' |pace |numeric | #' |pace_per40 |numeric | #' |possessions |numeric | #' |pie |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscoreadvancedv3(game_id = "1022200034") #' ``` wnba_boxscoreadvancedv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoreadvancedv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScoreAdvanced") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_advanced", "away_team_player_advanced", "home_team_totals_advanced", "away_team_totals_advanced" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no advanced boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Misc V3** #' @name wnba_boxscoremiscv3 NULL #' @title #' **Get WNBA Stats API Boxscore Misc V3** #' @rdname wnba_boxscoremiscv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: home_team_player_misc, away_team_player_misc, #' home_team_totals_misc, away_team_totals_misc #' #' **home_team_player_misc** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |points_off_turnovers |integer | #' |points_second_chance |integer | #' |points_fast_break |integer | #' |points_paint |integer | #' |opp_points_off_turnovers |integer | #' |opp_points_second_chance |integer | #' |opp_points_fast_break |integer | #' |opp_points_paint |integer | #' |blocks |integer | #' |blocks_against |integer | #' |fouls_personal |integer | #' |fouls_drawn |integer | #' #' **away_team_player_misc** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |points_off_turnovers |integer | #' |points_second_chance |integer | #' |points_fast_break |integer | #' |points_paint |integer | #' |opp_points_off_turnovers |integer | #' |opp_points_second_chance |integer | #' |opp_points_fast_break |integer | #' |opp_points_paint |integer | #' |blocks |integer | #' |blocks_against |integer | #' |fouls_personal |integer | #' |fouls_drawn |integer | #' #' **home_team_totals_misc** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |points_off_turnovers |integer | #' |points_second_chance |integer | #' |points_fast_break |integer | #' |points_paint |integer | #' |opp_points_off_turnovers |integer | #' |opp_points_second_chance |integer | #' |opp_points_fast_break |integer | #' |opp_points_paint |integer | #' |blocks |integer | #' |blocks_against |integer | #' |fouls_personal |integer | #' |fouls_drawn |integer | #' #' **away_team_totals_misc** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |points_off_turnovers |integer | #' |points_second_chance |integer | #' |points_fast_break |integer | #' |points_paint |integer | #' |opp_points_off_turnovers |integer | #' |opp_points_second_chance |integer | #' |opp_points_fast_break |integer | #' |opp_points_paint |integer | #' |blocks |integer | #' |blocks_against |integer | #' |fouls_personal |integer | #' |fouls_drawn |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscoremiscv3(game_id = "1022200034") #' ``` wnba_boxscoremiscv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoremiscv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScoreMisc") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_misc", "away_team_player_misc", "home_team_totals_misc", "away_team_totals_misc" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no misc boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Scoring V3** #' @name wnba_boxscorescoringv3 NULL #' @title #' **Get WNBA Stats API Boxscore Scoring V3** #' @rdname wnba_boxscorescoringv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: home_team_player_scoring, away_team_player_scoring, #' home_team_totals_scoring, away_team_totals_scoring #' #' **home_team_player_scoring** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |percentage_field_goals_attempted2pt |numeric | #' |percentage_field_goals_attempted3pt |numeric | #' |percentage_points2pt |numeric | #' |percentage_points_midrange2pt |numeric | #' |percentage_points3pt |numeric | #' |percentage_points_fast_break |numeric | #' |percentage_points_free_throw |numeric | #' |percentage_points_off_turnovers |numeric | #' |percentage_points_paint |numeric | #' |percentage_assisted2pt |numeric | #' |percentage_unassisted2pt |numeric | #' |percentage_assisted3pt |numeric | #' |percentage_unassisted3pt |numeric | #' |percentage_assisted_fgm |numeric | #' |percentage_unassisted_fgm |numeric | #' #' **away_team_player_scoring** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |percentage_field_goals_attempted2pt |numeric | #' |percentage_field_goals_attempted3pt |numeric | #' |percentage_points2pt |numeric | #' |percentage_points_midrange2pt |numeric | #' |percentage_points3pt |numeric | #' |percentage_points_fast_break |numeric | #' |percentage_points_free_throw |numeric | #' |percentage_points_off_turnovers |numeric | #' |percentage_points_paint |numeric | #' |percentage_assisted2pt |numeric | #' |percentage_unassisted2pt |numeric | #' |percentage_assisted3pt |numeric | #' |percentage_unassisted3pt |numeric | #' |percentage_assisted_fgm |numeric | #' |percentage_unassisted_fgm |numeric | #' #' **home_team_totals_scoring** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |percentage_field_goals_attempted2pt |numeric | #' |percentage_field_goals_attempted3pt |numeric | #' |percentage_points2pt |numeric | #' |percentage_points_midrange2pt |numeric | #' |percentage_points3pt |numeric | #' |percentage_points_fast_break |numeric | #' |percentage_points_free_throw |numeric | #' |percentage_points_off_turnovers |numeric | #' |percentage_points_paint |numeric | #' |percentage_assisted2pt |numeric | #' |percentage_unassisted2pt |numeric | #' |percentage_assisted3pt |numeric | #' |percentage_unassisted3pt |numeric | #' |percentage_assisted_fgm |numeric | #' |percentage_unassisted_fgm |numeric | #' #' **away_team_totals_scoring** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |percentage_field_goals_attempted2pt |numeric | #' |percentage_field_goals_attempted3pt |numeric | #' |percentage_points2pt |numeric | #' |percentage_points_midrange2pt |numeric | #' |percentage_points3pt |numeric | #' |percentage_points_fast_break |numeric | #' |percentage_points_free_throw |numeric | #' |percentage_points_off_turnovers |numeric | #' |percentage_points_paint |numeric | #' |percentage_assisted2pt |numeric | #' |percentage_unassisted2pt |numeric | #' |percentage_assisted3pt |numeric | #' |percentage_unassisted3pt |numeric | #' |percentage_assisted_fgm |numeric | #' |percentage_unassisted_fgm |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscorescoringv3(game_id = "1022200034") #' ``` wnba_boxscorescoringv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscorescoringv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScoreScoring") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_scoring", "away_team_player_scoring", "home_team_totals_scoring", "away_team_totals_scoring" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoring boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Four Factors V3** #' @name wnba_boxscorefourfactorsv3 NULL #' @title #' **Get WNBA Stats API Boxscore Four Factors V3** #' @rdname wnba_boxscorefourfactorsv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: home_team_player_four_factors, #' away_team_player_four_factors, home_team_totals_four_factors, #' away_team_totals_four_factors #' #' **home_team_player_four_factors** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |effective_field_goal_percentage |numeric | #' |free_throw_attempt_rate |numeric | #' |team_turnover_percentage |numeric | #' |offensive_rebound_percentage |numeric | #' |opp_effective_field_goal_percentage |numeric | #' |opp_free_throw_attempt_rate |numeric | #' |opp_team_turnover_percentage |numeric | #' |opp_offensive_rebound_percentage |numeric | #' #' **away_team_player_four_factors** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |effective_field_goal_percentage |numeric | #' |free_throw_attempt_rate |numeric | #' |team_turnover_percentage |numeric | #' |offensive_rebound_percentage |numeric | #' |opp_effective_field_goal_percentage |numeric | #' |opp_free_throw_attempt_rate |numeric | #' |opp_team_turnover_percentage |numeric | #' |opp_offensive_rebound_percentage |numeric | #' #' **home_team_totals_four_factors** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |effective_field_goal_percentage |numeric | #' |free_throw_attempt_rate |numeric | #' |team_turnover_percentage |numeric | #' |offensive_rebound_percentage |numeric | #' |opp_effective_field_goal_percentage |numeric | #' |opp_free_throw_attempt_rate |numeric | #' |opp_team_turnover_percentage |numeric | #' |opp_offensive_rebound_percentage |numeric | #' #' **away_team_totals_four_factors** #' #' #' |col_name |types | #' |:-----------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |effective_field_goal_percentage |numeric | #' |free_throw_attempt_rate |numeric | #' |team_turnover_percentage |numeric | #' |offensive_rebound_percentage |numeric | #' |opp_effective_field_goal_percentage |numeric | #' |opp_free_throw_attempt_rate |numeric | #' |opp_team_turnover_percentage |numeric | #' |opp_offensive_rebound_percentage |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscorefourfactorsv3(game_id = "1022200034") #' ``` wnba_boxscorefourfactorsv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscorefourfactorsv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScoreFourFactors") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_four_factors", "away_team_player_four_factors", "home_team_totals_four_factors", "away_team_totals_four_factors" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no four factors boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Player Tracking V3** #' @name wnba_boxscoreplayertrackv3 NULL #' @title #' **Get WNBA Stats API Boxscore Player Tracking V3** #' @rdname wnba_boxscoreplayertrackv3 #' @author Saiem Gilani #' @param game_id Game ID #' @param start_period start_period #' @param end_period end_period #' @param start_range start_range #' @param end_range end_range #' @param range_type range_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return A list of data frames: home_team_player_player_track, away_team_player_player_track, #' home_team_totals_player_track, away_team_totals_player_track #' #' **home_team_player_player_track** #' #' #' |col_name |types | #' |:-------------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |speed |numeric | #' |distance |numeric | #' |rebound_chances_offensive |integer | #' |rebound_chances_defensive |integer | #' |rebound_chances_total |integer | #' |touches |integer | #' |secondary_assists |integer | #' |free_throw_assists |integer | #' |passes |integer | #' |assists |integer | #' |contested_field_goals_made |integer | #' |contested_field_goals_attempted |integer | #' |contested_field_goal_percentage |numeric | #' |uncontested_field_goals_made |integer | #' |uncontested_field_goals_attempted |integer | #' |uncontested_field_goals_percentage |numeric | #' |field_goal_percentage |numeric | #' |defended_at_rim_field_goals_made |integer | #' |defended_at_rim_field_goals_attempted |integer | #' |defended_at_rim_field_goal_percentage |numeric | #' #' **away_team_player_player_track** #' #' #' |col_name |types | #' |:-------------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |speed |numeric | #' |distance |numeric | #' |rebound_chances_offensive |integer | #' |rebound_chances_defensive |integer | #' |rebound_chances_total |integer | #' |touches |integer | #' |secondary_assists |integer | #' |free_throw_assists |integer | #' |passes |integer | #' |assists |integer | #' |contested_field_goals_made |integer | #' |contested_field_goals_attempted |integer | #' |contested_field_goal_percentage |numeric | #' |uncontested_field_goals_made |integer | #' |uncontested_field_goals_attempted |integer | #' |uncontested_field_goals_percentage |numeric | #' |field_goal_percentage |numeric | #' |defended_at_rim_field_goals_made |integer | #' |defended_at_rim_field_goals_attempted |integer | #' |defended_at_rim_field_goal_percentage |numeric | #' #' **home_team_totals_player_track** #' #' #' |col_name |types | #' |:-------------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |distance |numeric | #' |rebound_chances_offensive |integer | #' |rebound_chances_defensive |integer | #' |rebound_chances_total |integer | #' |touches |integer | #' |secondary_assists |integer | #' |free_throw_assists |integer | #' |passes |integer | #' |assists |integer | #' |contested_field_goals_made |integer | #' |contested_field_goals_attempted |integer | #' |contested_field_goal_percentage |numeric | #' |uncontested_field_goals_made |integer | #' |uncontested_field_goals_attempted |integer | #' |uncontested_field_goals_percentage |numeric | #' |field_goal_percentage |numeric | #' |defended_at_rim_field_goals_made |integer | #' |defended_at_rim_field_goals_attempted |integer | #' |defended_at_rim_field_goal_percentage |numeric | #' #' **away_team_totals_player_track** #' #' #' |col_name |types | #' |:-------------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |distance |numeric | #' |rebound_chances_offensive |integer | #' |rebound_chances_defensive |integer | #' |rebound_chances_total |integer | #' |touches |integer | #' |secondary_assists |integer | #' |free_throw_assists |integer | #' |passes |integer | #' |assists |integer | #' |contested_field_goals_made |integer | #' |contested_field_goals_attempted |integer | #' |contested_field_goal_percentage |numeric | #' |uncontested_field_goals_made |integer | #' |uncontested_field_goals_attempted |integer | #' |uncontested_field_goals_percentage |numeric | #' |field_goal_percentage |numeric | #' |defended_at_rim_field_goals_made |integer | #' |defended_at_rim_field_goals_attempted |integer | #' |defended_at_rim_field_goal_percentage |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscoreplayertrackv3(game_id = "1022200034") #' ``` wnba_boxscoreplayertrackv3 <- function( game_id = "1022200034", start_period = 0, end_period = 14, start_range = 0, end_range = 0, range_type = 0, ...){ version <- "boxscoreplayertrackv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( EndPeriod = end_period, EndRange = end_range, GameID = pad_id(game_id), RangeType = range_type, StartPeriod = start_period, StartRange = start_range ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) data <- resp %>% purrr::pluck("boxScorePlayerTrack") %>% dplyr::as_tibble() ids_df <- data %>% data.frame() %>% dplyr::select("gameId","awayTeamId","homeTeamId") %>% dplyr::distinct() home_team_data <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_data %>% purrr::pluck("teamId"), team_name = home_team_data %>% purrr::pluck("teamName"), team_city = home_team_data %>% purrr::pluck("teamCity"), team_tricode = home_team_data %>% purrr::pluck("teamTricode"), team_slug = home_team_data %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) away_team_data <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_data %>% purrr::pluck("teamId"), team_name = away_team_data %>% purrr::pluck("teamName"), team_city = away_team_data %>% purrr::pluck("teamCity"), team_tricode = away_team_data %>% purrr::pluck("teamTricode"), team_slug = away_team_data %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_data %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_data %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_player_track", "away_team_player_player_track", "home_team_totals_player_track", "away_team_totals_player_track" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player tracking boxscore v3 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Boxscore Hustle V2** #' @name wnba_boxscorehustlev2 NULL #' @title #' **Get WNBA Stats API Boxscore Hustle V2** #' @rdname wnba_boxscorehustlev2 #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: home_team_player_hustle, away_team_player_hustle, #' home_team_hustle_totals, away_team_hustle_totals #' #' **home_team_player_hustle** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |points |integer | #' |contested_shots |integer | #' |contested_shots2pt |integer | #' |contested_shots3pt |integer | #' |deflections |integer | #' |charges_drawn |integer | #' |screen_assists |integer | #' |screen_assist_points |integer | #' |loose_balls_recovered_offensive |integer | #' |loose_balls_recovered_defensive |integer | #' |loose_balls_recovered_total |integer | #' |offensive_box_outs |integer | #' |defensive_box_outs |integer | #' |box_out_player_team_rebounds |integer | #' |box_out_player_rebounds |integer | #' |box_outs |integer | #' #' **away_team_player_hustle** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |person_id |integer | #' |first_name |character | #' |family_name |character | #' |name_i |character | #' |player_slug |character | #' |position |character | #' |comment |character | #' |jersey_num |character | #' |minutes |character | #' |points |integer | #' |contested_shots |integer | #' |contested_shots2pt |integer | #' |contested_shots3pt |integer | #' |deflections |integer | #' |charges_drawn |integer | #' |screen_assists |integer | #' |screen_assist_points |integer | #' |loose_balls_recovered_offensive |integer | #' |loose_balls_recovered_defensive |integer | #' |loose_balls_recovered_total |integer | #' |offensive_box_outs |integer | #' |defensive_box_outs |integer | #' |box_out_player_team_rebounds |integer | #' |box_out_player_rebounds |integer | #' |box_outs |integer | #' #' **home_team_totals_hustle** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |points |integer | #' |contested_shots |integer | #' |contested_shots2pt |integer | #' |contested_shots3pt |integer | #' |deflections |integer | #' |charges_drawn |integer | #' |screen_assists |integer | #' |screen_assist_points |integer | #' |loose_balls_recovered_offensive |integer | #' |loose_balls_recovered_defensive |integer | #' |loose_balls_recovered_total |integer | #' |offensive_box_outs |integer | #' |defensive_box_outs |integer | #' |box_out_player_team_rebounds |integer | #' |box_out_player_rebounds |integer | #' |box_outs |integer | #' #' **away_team_totals_hustle** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |game_id |character | #' |away_team_id |integer | #' |home_team_id |integer | #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_slug |character | #' |minutes |character | #' |points |integer | #' |contested_shots |integer | #' |contested_shots2pt |integer | #' |contested_shots3pt |integer | #' |deflections |integer | #' |charges_drawn |integer | #' |screen_assists |integer | #' |screen_assist_points |integer | #' |loose_balls_recovered_offensive |integer | #' |loose_balls_recovered_defensive |integer | #' |loose_balls_recovered_total |integer | #' |offensive_box_outs |integer | #' |defensive_box_outs |integer | #' |box_out_player_team_rebounds |integer | #' |box_out_player_rebounds |integer | #' |box_outs |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore V3 Functions #' @details #' ```r #' wnba_boxscorehustlev2(game_id = "1022200034") #' ``` wnba_boxscorehustlev2 <- function( game_id = "1022200034", ...){ version <- "boxscorehustlev2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = pad_id(game_id) ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) box_score_hustle <- resp %>% purrr::pluck("boxScoreHustle") ids_df <- data.frame( gameId = box_score_hustle %>% purrr::pluck("gameId"), awayTeamId = box_score_hustle %>% purrr::pluck("awayTeamId"), homeTeamId = box_score_hustle %>% purrr::pluck("homeTeamId") ) ids_df <- ids_df %>% dplyr::distinct() home_team_hustle <- box_score_hustle %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team_hustle %>% purrr::pluck("teamId"), team_name = home_team_hustle %>% purrr::pluck("teamName"), team_city = home_team_hustle %>% purrr::pluck("teamCity"), team_tricode = home_team_hustle %>% purrr::pluck("teamTricode"), team_slug = home_team_hustle %>% purrr::pluck("teamSlug") ) home_team_totals <- home_team_hustle %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) home_team_players <- home_team_hustle %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") home_team_totals <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Team Hustle Boxscore Information from WNBA.com", Sys.time()) home_team_players <- ids_df %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Home Player Hustle Boxscore Information from WNBA.com", Sys.time()) away_team_hustle <- box_score_hustle %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team_hustle %>% purrr::pluck("teamId"), team_name = away_team_hustle %>% purrr::pluck("teamName"), team_city = away_team_hustle %>% purrr::pluck("teamCity"), team_tricode = away_team_hustle %>% purrr::pluck("teamTricode"), team_slug = away_team_hustle %>% purrr::pluck("teamSlug") ) away_team_totals <- away_team_hustle %>% purrr::pluck("statistics") %>% data.frame(stringsAsFactors = F) away_team_players <- away_team_hustle %>% purrr::pluck("players") %>% data.frame(stringsAsFactors = F) %>% tidyr::unnest("statistics") away_team_totals <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_totals) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Team Hustle Boxscore Information from WNBA.com", Sys.time()) away_team_players <- ids_df %>% dplyr::bind_cols(away_team_info) %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Away Player Hustle Boxscore Information from WNBA.com", Sys.time()) df_list <- c( list(home_team_players), list(away_team_players), list(home_team_totals), list(away_team_totals) ) names(df_list) <- c( "home_team_player_hustle", "away_team_player_hustle", "home_team_totals_hustle", "away_team_totals_hustle" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no hustle stats boxscore v2 data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Game Rotation** #' @name wnba_gamerotation NULL #' @title #' **Get WNBA Stats API Game Rotation** #' @rdname wnba_gamerotation #' @author Saiem Gilani #' @param game_id Game ID #' @param league_id League ID #' @param rotation_stat Rotation stat to provide details on: PLAYER_PTS, PT_DIFF, USG_PCT #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: AwayTeam, HomeTeam #' #' **AwayTeam** #' #' #' |col_name |types | #' |:-------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |PERSON_ID |character | #' |PLAYER_FIRST |character | #' |PLAYER_LAST |character | #' |IN_TIME_REAL |character | #' |OUT_TIME_REAL |character | #' |PLAYER_PTS |character | #' |PT_DIFF |character | #' |USG_PCT |character | #' #' **HomeTeam** #' #' #' |col_name |types | #' |:-------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |PERSON_ID |character | #' |PLAYER_FIRST |character | #' |PLAYER_LAST |character | #' |IN_TIME_REAL |character | #' |OUT_TIME_REAL |character | #' |PLAYER_PTS |character | #' |PT_DIFF |character | #' |USG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Boxscore Functions #' @family WNBA Lineup Functions #' @details #' ```r #' wnba_gamerotation(game_id = "1022200034") #' ``` wnba_gamerotation <- function( game_id, league_id = '10', rotation_stat = 'PLAYER_PTS', ...){ version <- "gamerotation" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = pad_id(game_id), LeagueID = league_id, RotationStat = rotation_stat ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no game rotation data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } ## wnba_boxscoredefensivev2 # #' **Get WNBA Stats API Boxscore Defensive V2** # #' @name wnba_boxscoredefensivev2 # NULL # #' @title # #' **Get WNBA Stats API Boxscore Defensive V2** # #' @rdname wnba_boxscoredefensivev2 # #' @author Saiem Gilani # #' @param game_id Game ID # #' @param start_period start_period # #' @param end_period end_period # #' @param start_range start_range # #' @param end_range end_range # #' @param range_type range_type # #' @param ... Additional arguments passed to an underlying function like httr. # #' @return A list of data frames: home_team_player_defensive, away_team_player_defensive, # #' home_team_totals_defensive, away_team_totals_defensive # #' # #' **home_team_player_defensive** # #' # #' # #' |col_name |types | # #' |:--------------------------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' |person_id |integer | # #' |first_name |character | # #' |family_name |character | # #' |name_i |character | # #' |player_slug |character | # #' |position |character | # #' |comment |character | # #' |jersey_num |character | # #' |matchup_minutes |character | # #' |partial_possessions |numeric | # #' |switches_on |integer | # #' |player_points |integer | # #' |defensive_rebounds |integer | # #' |matchup_assists |integer | # #' |matchup_turnovers |integer | # #' |steals |integer | # #' |blocks |integer | # #' |matchup_field_goals_made |integer | # #' |matchup_field_goals_attempted |integer | # #' |matchup_field_goal_percentage |numeric | # #' |matchup_three_pointers_made |integer | # #' |matchup_three_pointers_attempted |integer | # #' |matchup_three_pointer_percentage |numeric | # #' # #' **away_team_player_defensive** # #' # #' # #' |col_name |types | # #' |:--------------------------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' |person_id |integer | # #' |first_name |character | # #' |family_name |character | # #' |name_i |character | # #' |player_slug |character | # #' |position |character | # #' |comment |character | # #' |jersey_num |character | # #' |matchup_minutes |character | # #' |partial_possessions |numeric | # #' |switches_on |integer | # #' |player_points |integer | # #' |defensive_rebounds |integer | # #' |matchup_assists |integer | # #' |matchup_turnovers |integer | # #' |steals |integer | # #' |blocks |integer | # #' |matchup_field_goals_made |integer | # #' |matchup_field_goals_attempted |integer | # #' |matchup_field_goal_percentage |numeric | # #' |matchup_three_pointers_made |integer | # #' |matchup_three_pointers_attempted |integer | # #' |matchup_three_pointer_percentage |numeric | # #' # #' **home_team_totals_defensive** # #' # #' # #' |col_name |types | # #' |:------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' # #' **away_team_totals_defensive** # #' # #' # #' |col_name |types | # #' |:------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' # #' @importFrom jsonlite fromJSON toJSON # #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble # #' @import rvest # #' @export # #' @family WNBA Boxscore V3 Functions # #' @details # #' ```r # #' wnba_boxscoredefensivev2(game_id = "1022200034") # #' ``` # wnba_boxscoredefensivev2 <- function( # game_id = "1022200034", # start_period = 0, # end_period = 14, # start_range = 0, # end_range = 0, # range_type = 0, # ...){ # # version <- "boxscoredefensivev2" # endpoint <- wnba_endpoint(version) # full_url <- endpoint # # params <- list( # EndPeriod = end_period, # EndRange = end_range, # GameID = pad_id(game_id), # RangeType = range_type, # StartPeriod = start_period, # StartRange = start_range # ) # # tryCatch( # expr = { # # resp <- request_with_proxy(url = full_url, params = params) # # data <- resp %>% # purrr::pluck("boxScoreDefensive") %>% # dplyr::as_tibble() # # ids_df <- data %>% # data.frame() %>% # dplyr::select("gameId","awayTeamId","homeTeamId") %>% # dplyr::distinct() # # home_team_data <- data %>% # purrr::pluck("homeTeam") # # home_team_info <- data.frame( # team_id = home_team_data %>% purrr::pluck("teamId"), # team_name = home_team_data %>% purrr::pluck("teamName"), # team_city = home_team_data %>% purrr::pluck("teamCity"), # team_tricode = home_team_data %>% purrr::pluck("teamTricode"), # team_slug = home_team_data %>% purrr::pluck("teamSlug") # ) # # home_team_totals <- home_team_data %>% # purrr::pluck("statistics") %>% # data.frame(stringsAsFactors = F) # # home_team_players <- home_team_data %>% # purrr::pluck("players") %>% # data.frame(stringsAsFactors = F) %>% # tidyr::unnest("statistics") # # home_team_totals <- ids_df %>% # dplyr::bind_cols(home_team_info) %>% # dplyr::bind_cols(home_team_totals) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Home Team Boxscore Information from WNBA.com", Sys.time()) # # home_team_players <- ids_df %>% # dplyr::bind_cols(home_team_info) %>% # dplyr::bind_cols(home_team_players) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) # # # away_team_data <- data %>% # purrr::pluck("awayTeam") # # away_team_info <- data.frame( # team_id = away_team_data %>% purrr::pluck("teamId"), # team_name = away_team_data %>% purrr::pluck("teamName"), # team_city = away_team_data %>% purrr::pluck("teamCity"), # team_tricode = away_team_data %>% purrr::pluck("teamTricode"), # team_slug = away_team_data %>% purrr::pluck("teamSlug") # ) # # away_team_totals <- away_team_data %>% # purrr::pluck("statistics") %>% # data.frame(stringsAsFactors = F) # # away_team_players <- away_team_data %>% # purrr::pluck("players") %>% # data.frame(stringsAsFactors = F) %>% # tidyr::unnest("statistics") # # away_team_totals <- ids_df %>% # dplyr::bind_cols(away_team_info) %>% # dplyr::bind_cols(away_team_totals) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Away Team Boxscore Information from WNBA.com", Sys.time()) # # away_team_players <- ids_df %>% # dplyr::bind_cols(away_team_info) %>% # dplyr::bind_cols(away_team_players) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) # # df_list <- c( # list(home_team_players), # list(away_team_players), # list(home_team_totals), # list(away_team_totals) # ) # names(df_list) <- c( # "home_team_player_defensive", # "away_team_player_defensive", # "home_team_totals_defensive", # "away_team_totals_defensive" # ) # # }, # error = function(e) { # message(glue::glue("{Sys.time()}: Invalid arguments or no defensive boxscore v2 data for {game_id} available!")) # }, # warning = function(w) { # }, # finally = { # } # ) # return(df_list) # } ## wnba_boxscorematchupsv3 # #' **Get WNBA Stats API Boxscore Matchups V3** # #' @name wnba_boxscorematchupsv3 # NULL # #' @title # #' **Get WNBA Stats API Boxscore Matchups V3** # #' @rdname wnba_boxscorematchupsv3 # #' @author Saiem Gilani # #' @param game_id Game ID # #' @param start_period start_period # #' @param end_period end_period # #' @param start_range start_range # #' @param end_range end_range # #' @param range_type range_type # #' @param ... Additional arguments passed to an underlying function like httr. # #' @return A list of data frames: home_team_player_matchups, away_team_player_matchups # #' # #' **home_team_player_matchups** # #' # #' # #' |col_name |types | # #' |:---------------------------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' |person_id |integer | # #' |first_name |character | # #' |family_name |character | # #' |name_i |character | # #' |player_slug |character | # #' |position |character | # #' |comment |character | # #' |jersey_num |character | # #' |matchups_person_id |integer | # #' |matchups_first_name |character | # #' |matchups_family_name |character | # #' |matchups_name_i |character | # #' |matchups_player_slug |character | # #' |matchups_jersey_num |character | # #' |matchup_minutes |character | # #' |matchup_minutes_sort |numeric | # #' |partial_possessions |numeric | # #' |percentage_defender_total_time |numeric | # #' |percentage_offensive_total_time |numeric | # #' |percentage_total_time_both_on |numeric | # #' |switches_on |integer | # #' |player_points |integer | # #' |team_points |integer | # #' |matchup_assists |integer | # #' |matchup_potential_assists |integer | # #' |matchup_turnovers |integer | # #' |matchup_blocks |integer | # #' |matchup_field_goals_made |integer | # #' |matchup_field_goals_attempted |integer | # #' |matchup_field_goals_percentage |numeric | # #' |matchup_three_pointers_made |integer | # #' |matchup_three_pointers_attempted |integer | # #' |matchup_three_pointers_percentage |numeric | # #' |help_blocks |integer | # #' |help_field_goals_made |integer | # #' |help_field_goals_attempted |integer | # #' |help_field_goals_percentage |numeric | # #' |matchup_free_throws_made |integer | # #' |matchup_free_throws_attempted |integer | # #' |shooting_fouls |integer | # #' # #' **away_team_player_matchups** # #' # #' # #' |col_name |types | # #' |:---------------------------------|:---------| # #' |game_id |character | # #' |away_team_id |integer | # #' |home_team_id |integer | # #' |team_id |integer | # #' |team_name |character | # #' |team_city |character | # #' |team_tricode |character | # #' |team_slug |character | # #' |person_id |integer | # #' |first_name |character | # #' |family_name |character | # #' |name_i |character | # #' |player_slug |character | # #' |position |character | # #' |comment |character | # #' |jersey_num |character | # #' |matchups_person_id |integer | # #' |matchups_first_name |character | # #' |matchups_family_name |character | # #' |matchups_name_i |character | # #' |matchups_player_slug |character | # #' |matchups_jersey_num |character | # #' |matchup_minutes |character | # #' |matchup_minutes_sort |numeric | # #' |partial_possessions |numeric | # #' |percentage_defender_total_time |numeric | # #' |percentage_offensive_total_time |numeric | # #' |percentage_total_time_both_on |numeric | # #' |switches_on |integer | # #' |player_points |integer | # #' |team_points |integer | # #' |matchup_assists |integer | # #' |matchup_potential_assists |integer | # #' |matchup_turnovers |integer | # #' |matchup_blocks |integer | # #' |matchup_field_goals_made |integer | # #' |matchup_field_goals_attempted |integer | # #' |matchup_field_goals_percentage |numeric | # #' |matchup_three_pointers_made |integer | # #' |matchup_three_pointers_attempted |integer | # #' |matchup_three_pointers_percentage |numeric | # #' |help_blocks |integer | # #' |help_field_goals_made |integer | # #' |help_field_goals_attempted |integer | # #' |help_field_goals_percentage |numeric | # #' |matchup_free_throws_made |integer | # #' |matchup_free_throws_attempted |integer | # #' |shooting_fouls |integer | # #' # #' @importFrom jsonlite fromJSON toJSON # #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble # #' @import rvest # #' @export # #' @family WNBA Boxscore V3 Functions # #' @details # #' (No Matchups Data for WNBA yet, so defunct) # #' ```r # #' wnba_boxscorematchupsv3(game_id = "1022200034") # #' ``` # wnba_boxscorematchupsv3 <- function( # game_id = "1022200034", # start_period = 0, # end_period = 14, # start_range = 0, # end_range = 0, # range_type = 0, # ...){ # # version <- "boxscorematchupsv3" # endpoint <- wnba_endpoint(version) # full_url <- endpoint # # params <- list( # EndPeriod = end_period, # EndRange = end_range, # GameID = pad_id(game_id), # RangeType = range_type, # StartPeriod = start_period, # StartRange = start_range # ) # # tryCatch( # expr = { # # resp <- request_with_proxy(url = full_url, params = params) # # data <- resp %>% # purrr::pluck("boxScoreMatchups") %>% # dplyr::as_tibble() # # ids_df <- data %>% # data.frame() %>% # dplyr::select("gameId","awayTeamId","homeTeamId") %>% # dplyr::distinct() # # home_team_data <- data %>% # purrr::pluck("homeTeam") # if (is.null(home_team_data$teamCity)) { # return(message(glue::glue("{Sys.time()}: No matchups boxscore v3 data for {game_id} available!"))) # } # home_team_info <- data.frame( # team_id = home_team_data %>% purrr::pluck("teamId"), # team_name = home_team_data %>% purrr::pluck("teamName"), # team_city = home_team_data %>% purrr::pluck("teamCity"), # team_tricode = home_team_data %>% purrr::pluck("teamTricode"), # team_slug = home_team_data %>% purrr::pluck("teamSlug") # ) # # home_team_players <- home_team_data %>% # purrr::pluck("players") %>% # data.frame(stringsAsFactors = F) %>% # tidyr::unnest("matchups", names_sep = "_") %>% # tidyr::unnest("matchups_statistics") # # home_team_players <- ids_df %>% # dplyr::bind_cols(home_team_info) %>% # dplyr::bind_cols(home_team_players) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Home Player Boxscore Information from WNBA.com", Sys.time()) # # # away_team_data <- data %>% # purrr::pluck("awayTeam") # # away_team_info <- data.frame( # team_id = away_team_data %>% purrr::pluck("teamId"), # team_name = away_team_data %>% purrr::pluck("teamName"), # team_city = away_team_data %>% purrr::pluck("teamCity"), # team_tricode = away_team_data %>% purrr::pluck("teamTricode"), # team_slug = away_team_data %>% purrr::pluck("teamSlug") # ) # # away_team_players <- away_team_data %>% # purrr::pluck("players") %>% # data.frame(stringsAsFactors = F) %>% # tidyr::unnest("matchups", names_sep = "_") %>% # tidyr::unnest("matchups_statistics") # # away_team_players <- ids_df %>% # dplyr::bind_cols(away_team_info) %>% # dplyr::bind_cols(away_team_players) %>% # janitor::clean_names() %>% # make_wehoop_data("WNBA Away Player Boxscore Information from WNBA.com", Sys.time()) # # df_list <- c( # list(home_team_players), # list(away_team_players) # ) # names(df_list) <- c( # "home_team_player_matchups", # "away_team_player_matchups" # ) # # }, # error = function(e) { # message(glue::glue("{Sys.time()}: Invalid arguments or no matchups boxscore v3 data for {game_id} available!")) # }, # warning = function(w) { # }, # finally = { # } # ) # return(df_list) # }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_boxscore_v3.R
#' **Get WNBA Stats API Cumulative Player Stats** #' @name wnba_cumestatsplayer NULL #' @title #' **Get WNBA Stats API Cumulative Player Stats** #' @rdname wnba_cumestatsplayer #' @author Saiem Gilani #' @param game_ids game_ids #' @param league_id league_id #' @param player_id player_id #' @param season season #' @param season_type season_type #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: GameByGameStats, TotalPlayerStats #' #' **GameByGameStats** #' #' #' |col_name |types | #' |:--------------|:---------| #' |DATE_EST |character | #' |VISITOR_TEAM |character | #' |HOME_TEAM |character | #' |GP |character | #' |GS |character | #' |ACTUAL_MINUTES |character | #' |ACTUAL_SECONDS |character | #' |FG |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3 |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FT |character | #' |FTA |character | #' |FT_PCT |character | #' |OFF_REB |character | #' |DEF_REB |character | #' |TOT_REB |character | #' |AVG_TOT_REB |character | #' |AST |character | #' |PF |character | #' |DQ |character | #' |STL |character | #' |TURNOVERS |character | #' |BLK |character | #' |PTS |character | #' |AVG_PTS |character | #' #' **TotalPlayerStats** #' #' #' |col_name |types | #' |:------------------|:---------| #' |DISPLAY_FI_LAST |character | #' |PERSON_ID |character | #' |JERSEY_NUM |character | #' |GP |character | #' |GS |character | #' |ACTUAL_MINUTES |character | #' |ACTUAL_SECONDS |character | #' |FG |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3 |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FT |character | #' |FTA |character | #' |FT_PCT |character | #' |OFF_REB |character | #' |DEF_REB |character | #' |TOT_REB |character | #' |AST |character | #' |PF |character | #' |DQ |character | #' |STL |character | #' |TURNOVERS |character | #' |BLK |character | #' |PTS |character | #' |MAX_ACTUAL_MINUTES |character | #' |MAX_ACTUAL_SECONDS |character | #' |MAX_REB |character | #' |MAX_AST |character | #' |MAX_STL |character | #' |MAX_TURNOVERS |character | #' |MAX_BLK |character | #' |MAX_PTS |character | #' |AVG_ACTUAL_MINUTES |character | #' |AVG_ACTUAL_SECONDS |character | #' |AVG_TOT_REB |character | #' |AVG_AST |character | #' |AVG_STL |character | #' |AVG_TURNOVERS |character | #' |AVG_BLK |character | #' |AVG_PTS |character | #' |PER_MIN_TOT_REB |character | #' |PER_MIN_AST |character | #' |PER_MIN_STL |character | #' |PER_MIN_TURNOVERS |character | #' |PER_MIN_BLK |character | #' |PER_MIN_PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Cume Functions #' @details #' ```r #' wnba_cumestatsplayer(game_ids = "1022200018", player_id = "204319", season = "2021-22") #' ``` wnba_cumestatsplayer <- function( game_ids = '1022200018', league_id = '10', player_id = '204319', season = '2021-22', season_type = 'Regular Season', team_id = '', ...){ #intentional # season_type <- gsub(' ','+',season_type) version <- "cumestatsplayer" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameIDs = game_ids, LeagueID = league_id, PlayerID = player_id, Season = season, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no cumulative player stats data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Cumulative Player Game Stats** #' @name wnba_cumestatsplayergames NULL #' @title #' **Get WNBA Stats API Cumulative Player Game Stats** #' @rdname wnba_cumestatsplayergames #' @author Saiem Gilani #' @param league_id league_id #' @param location location #' @param outcome outcome #' @param player_id player_id #' @param season season #' @param season_type season_type #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_team_id vs_team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: CumeStatsPlayerGames #' #' **CumeStatsPlayerGames** #' #' #' |col_name |types | #' |:--------|:---------| #' |MATCHUP |character | #' |GAME_ID |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Cume Functions #' @details #' ```r #' wnba_cumestatsplayergames(player_id = "204319", season = "2021-22") #' ``` wnba_cumestatsplayergames <- function( league_id = '10', location = '', outcome = '', player_id = '204319', season = '2021-22', season_type = 'Regular Season', vs_conference = '', vs_division = '', vs_team_id = '', ...){ #intentional # season_type <- gsub(' ','+',season_type) version <- "cumestatsplayergames" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Location = location, Outcome = outcome, PlayerID = player_id, Season = season, SeasonType = season_type, VsConference = vs_conference, VsDivision = vs_division, VsTeamID = vs_team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no cumulative player game stats data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Cumulative Team Stats** #' @name wnba_cumestatsteam NULL #' @title #' **Get WNBA Stats API Cumulative Team Stats** #' @rdname wnba_cumestatsteam #' @author Saiem Gilani #' @param game_ids game_ids #' @param league_id league_id #' @param season season #' @param season_type season_type #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: GameByGameStats, TotalTeamStats #' #' **GameByGameStats** #' #' #' |col_name |types | #' |:------------------|:---------| #' |JERSEY_NUM |character | #' |PLAYER |character | #' |PERSON_ID |character | #' |TEAM_ID |character | #' |GP |character | #' |GS |character | #' |ACTUAL_MINUTES |character | #' |ACTUAL_SECONDS |character | #' |FG |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3 |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FT |character | #' |FTA |character | #' |FT_PCT |character | #' |OFF_REB |character | #' |DEF_REB |character | #' |TOT_REB |character | #' |AST |character | #' |PF |character | #' |DQ |character | #' |STL |character | #' |TURNOVERS |character | #' |BLK |character | #' |PTS |character | #' |MAX_ACTUAL_MINUTES |character | #' |MAX_ACTUAL_SECONDS |character | #' |MAX_REB |character | #' |MAX_AST |character | #' |MAX_STL |character | #' |MAX_TURNOVERS |character | #' |MAX_BLKP |character | #' |MAX_PTS |character | #' |AVG_ACTUAL_MINUTES |character | #' |AVG_ACTUAL_SECONDS |character | #' |AVG_REB |character | #' |AVG_AST |character | #' |AVG_STL |character | #' |AVG_TURNOVERS |character | #' |AVG_BLKP |character | #' |AVG_PTS |character | #' |PER_MIN_REB |character | #' |PER_MIN_AST |character | #' |PER_MIN_STL |character | #' |PER_MIN_TURNOVERS |character | #' |PER_MIN_BLK |character | #' |PER_MIN_PTS |character | #' #' **TotalTeamStats** #' #' #' |col_name |types | #' |:---------------|:---------| #' |CITY |character | #' |NICKNAME |character | #' |TEAM_ID |character | #' |W |character | #' |L |character | #' |W_HOME |character | #' |L_HOME |character | #' |W_ROAD |character | #' |L_ROAD |character | #' |TEAM_TURNOVERS |character | #' |TEAM_REBOUNDS |character | #' |GP |character | #' |GS |character | #' |ACTUAL_MINUTES |character | #' |ACTUAL_SECONDS |character | #' |FG |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3 |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FT |character | #' |FTA |character | #' |FT_PCT |character | #' |OFF_REB |character | #' |DEF_REB |character | #' |TOT_REB |character | #' |AST |character | #' |PF |character | #' |STL |character | #' |TOTAL_TURNOVERS |character | #' |BLK |character | #' |PTS |character | #' |AVG_REB |character | #' |AVG_PTS |character | #' |DQ |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Cume Functions #' @details #' ```r #' wnba_cumestatsteam(game_ids = "1022200018", season = "2021-22", team_id = "1611661317") #' ``` wnba_cumestatsteam <- function( game_ids = '1022200018', league_id = '10', season = '2021-22', season_type = 'Regular Season', team_id = '1611661317', ...){ #intentional # season_type <- gsub(' ','+',season_type) version <- "cumestatsteam" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameIDs = game_ids, LeagueID = league_id, Season = season, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no cumulative team stats data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Cumulative Team Game Stats** #' @name wnba_cumestatsteamgames NULL #' @title #' **Get WNBA Stats API Cumulative Team Game Stats** #' @rdname wnba_cumestatsteamgames #' @author Saiem Gilani #' @param league_id league_id #' @param location location #' @param outcome outcome #' @param season season #' @param season_id season_id #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_team_id vs_team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: CumeStatsTeamGames #' #' **CumeStatsTeamGames** #' #' #' |col_name |types | #' |:--------|:---------| #' |MATCHUP |character | #' |GAME_ID |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Cume Functions #' @details #' ```r #' wnba_cumestatsteamgames(team_id = 1611661317, season = "2021-22") #' `` wnba_cumestatsteamgames <- function( league_id = '10', location = '', outcome = '', season = '2021-22', season_id = '', season_type = 'Regular Season', team_id = 1611661317, vs_conference = '', vs_division = '', vs_team_id = '', ...){ #intentional # season_type <- gsub(' ','+',season_type) version <- "cumestatsteamgames" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Location = location, Outcome = outcome, Season = season, SeasonID = season_id, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsTeamID = vs_team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no cumulative team game stats data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_cume.R
#' **Get WNBA Stats API Draft Board** #' @name wnba_draftboard NULL #' @title #' **Get WNBA Stats API Draft Board** #' @rdname wnba_draftboard #' @author Saiem Gilani #' @param season season #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: teams,draft_info, picks #' #' **teams** #' #' #' |col_name |types | #' |:-------------|:---------| #' |id |integer | #' |external-id |character | #' |slug |character | #' |name |character | #' |city |character | #' |state |character | #' |url |character | #' |primarycolor |character | #' |seconarycolor |character | #' #' **draft_info** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |draft_status |character | #' |draft_modified |integer | #' |draft_title |character | #' |draft_show_players |character | #' |draft_id |integer | #' |draft_url |character | #' |draft_location |character | #' |sponsor_logo |character | #' |header_image |character | #' |sponsor_link |character | #' |draft_date |character | #' |draft_time_hh |character | #' |draft_time_mm |character | #' |draft_time_am |character | #' |draft_time_tz |character | #' |draft_round_1_channel |character | #' |draft_round_2_channel |character | #' |draft_round_3_channel |character | #' |draft_interval |character | #' #' **picks** #' #' #' |col_name |types | #' |:---------------|:---------| #' |team |character | #' |details |character | #' |player_name |character | #' |player_id |integer | #' |player_college |character | #' |player_position |character | #' |player_ppg |character | #' |player_rpg |character | #' |player_apg |character | #' |player_fg |character | #' |player_headshot |character | #' |player_url |character | #' |round |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' ```r #' wnba_draftboard(season = most_recent_wnba_season() - 1) #' ``` wnba_draftboard <- function( season = most_recent_wnba_season() - 1, ...){ version <- "draftboard" endpoint <- "https://www.wnba.com/wp-json/api/v1/get_draft_board" full_url <- endpoint params <- list( season = season ) tryCatch( expr = { res <- httr::RETRY("GET", full_url, query = params, ...) resp <- res %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() teams <- data.table::rbindlist(resp$teams) draft <- dplyr::bind_rows(resp$draft) rounds <- resp$rounds rounds$draft_lineup <- NULL rounds_df <- purrr::map_df(1:length(rounds),function(x){ rounds[[x]] %>% tidyr::unnest("player", names_sep = "_") %>% dplyr::mutate(round = x) }) df_list <- c(list(teams),list(draft),list(rounds_df)) names(df_list) <- c("teams","draft_info","picks") }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft board data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Draft Combine Stats** #' @name wnba_draftcombinestats NULL #' @title #' **Get WNBA Stats API Draft Combine Stats** #' @rdname wnba_draftcombinestats #' @author Saiem Gilani #' @param league_id league_id #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: DraftCombineStats #' #' **DraftCombineStats** #' #' #' |col_name |types | #' |:----------------------------|:---------| #' |SEASON |character | #' |PLAYER_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |PLAYER_NAME |character | #' |POSITION |character | #' |HEIGHT_WO_SHOES |character | #' |HEIGHT_WO_SHOES_FT_IN |character | #' |HEIGHT_W_SHOES |character | #' |HEIGHT_W_SHOES_FT_IN |character | #' |WEIGHT |character | #' |WINGSPAN |character | #' |WINGSPAN_FT_IN |character | #' |STANDING_REACH |character | #' |STANDING_REACH_FT_IN |character | #' |BODY_FAT_PCT |character | #' |HAND_LENGTH |character | #' |HAND_WIDTH |character | #' |STANDING_VERTICAL_LEAP |character | #' |MAX_VERTICAL_LEAP |character | #' |LANE_AGILITY_TIME |character | #' |MODIFIED_LANE_AGILITY_TIME |character | #' |THREE_QUARTER_SPRINT |character | #' |BENCH_PRESS |character | #' |SPOT_FIFTEEN_CORNER_LEFT |character | #' |SPOT_FIFTEEN_BREAK_LEFT |character | #' |SPOT_FIFTEEN_TOP_KEY |character | #' |SPOT_FIFTEEN_BREAK_RIGHT |character | #' |SPOT_FIFTEEN_CORNER_RIGHT |character | #' |SPOT_COLLEGE_CORNER_LEFT |character | #' |SPOT_COLLEGE_BREAK_LEFT |character | #' |SPOT_COLLEGE_TOP_KEY |character | #' |SPOT_COLLEGE_BREAK_RIGHT |character | #' |SPOT_COLLEGE_CORNER_RIGHT |character | #' |SPOT_NBA_CORNER_LEFT |character | #' |SPOT_NBA_BREAK_LEFT |character | #' |SPOT_NBA_TOP_KEY |character | #' |SPOT_NBA_BREAK_RIGHT |character | #' |SPOT_NBA_CORNER_RIGHT |character | #' |OFF_DRIB_FIFTEEN_BREAK_LEFT |character | #' |OFF_DRIB_FIFTEEN_TOP_KEY |character | #' |OFF_DRIB_FIFTEEN_BREAK_RIGHT |character | #' |OFF_DRIB_COLLEGE_BREAK_LEFT |character | #' |OFF_DRIB_COLLEGE_TOP_KEY |character | #' |OFF_DRIB_COLLEGE_BREAK_RIGHT |character | #' |ON_MOVE_FIFTEEN |character | #' |ON_MOVE_COLLEGE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' ```r #' wnba_draftcombinestats(season_year = most_recent_wnba_season() - 1) #' ``` wnba_draftcombinestats <- function( league_id = '10', season_year = most_recent_wnba_season() - 1, ...){ version <- "draftcombinestats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft combine stats data available for {season_year}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Draft Combine Drill Results** #' @name wnba_draftcombinedrillresults NULL #' @title #' **Get WNBA Stats API Draft Combine Drill Results** #' @rdname wnba_draftcombinedrillresults #' @author Saiem Gilani #' @param league_id league_id #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Results #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' (Possibly Defunct) #' ```r #' wnba_draftcombinedrillresults(season_year = most_recent_wnba_season() - 2) #' ``` wnba_draftcombinedrillresults <- function( league_id = '10', season_year = most_recent_wnba_season() - 1, ...){ version <- "draftcombinedrillresults" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft combine drill results data available for {season_year}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Draft Combine Non-Stationary Shooting** #' @name wnba_draftcombinenonstationaryshooting NULL #' @title #' **Get WNBA Stats API Draft Combine Non-Stationary Shooting** #' @rdname wnba_draftcombinenonstationaryshooting #' @author Saiem Gilani #' @param league_id league_id #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Results #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' (Possibly Defunct) #' ```r #' wnba_draftcombinenonstationaryshooting(season_year = most_recent_wnba_season() - 2) #' ``` wnba_draftcombinenonstationaryshooting <- function( league_id = '10', season_year = most_recent_wnba_season() - 1, ...){ version <- "draftcombinenonstationaryshooting" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft combine stationary shooting data available for {season_year}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Draft Combine Player Anthropological Measurements** #' @name wnba_draftcombineplayeranthro NULL #' @title #' **Get WNBA Stats API Draft Combine Player Anthropological Measurements** #' @rdname wnba_draftcombineplayeranthro #' @author Saiem Gilani #' @param league_id league_id #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Results #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' (Possibly Defunct) #' ```r #' wnba_draftcombineplayeranthro(season_year = most_recent_wnba_season() - 2) #' ``` wnba_draftcombineplayeranthro <- function( league_id = '10', season_year = most_recent_wnba_season() - 1, ...){ version <- "draftcombineplayeranthro" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft combine player anthropological data available for {season_year}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Draft Combine - Spot Shooting** #' @name wnba_draftcombinespotshooting NULL #' @title #' **Get WNBA Stats API Draft Combine - Spot Shooting** #' @rdname wnba_draftcombinespotshooting #' @author Saiem Gilani #' @param league_id league_id #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Results #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' (Possibly Defunct) #' ```r #' wnba_draftcombinespotshooting(season_year = most_recent_wnba_season() - 2) #' ``` wnba_draftcombinespotshooting <- function( league_id = '10', season_year = most_recent_wnba_season() - 1, ...){ version <- "draftcombinespotshooting" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft combine spot shooting data available for {season_year}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' @title #' **Get WNBA Stats API Draft History** #' @rdname wnba_drafthistory #' @author Saiem Gilani #' @param league_id league_id #' @param college college #' @param overall_pick overall_pick #' @param round_pick round_pick #' @param round_num round_num #' @param season season #' @param team_id team_id #' @param top_x top_x #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: DraftHistory #' #' **DraftHistory** #' #' #' |col_name |types | #' |:-------------------|:---------| #' |PERSON_ID |character | #' |PLAYER_NAME |character | #' |SEASON |character | #' |ROUND_NUMBER |character | #' |ROUND_PICK |character | #' |OVERALL_PICK |character | #' |DRAFT_TYPE |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |ORGANIZATION |character | #' |ORGANIZATION_TYPE |character | #' |PLAYER_PROFILE_FLAG |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Draft Functions #' @details #' ```r #' wnba_drafthistory(season = most_recent_wnba_season() - 1) #' ``` wnba_drafthistory <- function( league_id = '10', college = '', overall_pick = '', round_pick = '', round_num = '', season = most_recent_wnba_season() - 1, team_id = '', top_x = '', ...){ version <- "drafthistory" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, LeagueID = league_id, OverallPick = overall_pick, RoundNum = round_num, RoundPick = round_pick, Season = season, TeamID = team_id, TopX = top_x ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no draft history data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_draft.R
#' **Get WNBA Stats API Franchise Leaders** #' @name wnba_franchiseleaders NULL #' @title #' **Get WNBA Stats API Franchise Leaders** #' @rdname wnba_franchiseleaders #' @author Saiem Gilani #' @param league_id league_id #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: FranchiseLeaders #' #' **FranchiseLeaders** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |PTS |character | #' |PTS_PERSON_ID |character | #' |PTS_PLAYER |character | #' |AST |character | #' |AST_PERSON_ID |character | #' |AST_PLAYER |character | #' |REB |character | #' |REB_PERSON_ID |character | #' |REB_PLAYER |character | #' |BLK |character | #' |BLK_PERSON_ID |character | #' |BLK_PLAYER |character | #' |STL |character | #' |STL_PERSON_ID |character | #' |STL_PLAYER |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Franchise Functions #' @details #' [Franchise Leaders](https://stats.wnba.com/team/1611661324/franchise-leaders) #' ```r #' wnba_franchiseleaders(league_id = '10', team_id = '1611661324') #' ``` wnba_franchiseleaders <- function( league_id = '10', team_id = '1611661324', ...){ version <- "franchiseleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no franchise leaders data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Franchise Leaders with Rank** #' @name wnba_franchiseleaderswrank NULL #' @title #' **Get WNBA Stats API Franchise Leaders with Rank** #' @rdname wnba_franchiseleaderswrank #' @author Saiem Gilani #' @param league_id league_id #' @param per_mode per_mode #' @param season_type season_type #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: FranchiseLeaderswRank #' #' **FranchiseLeaderswRank** #' #' #' |col_name |types | #' |:----------------|:---------| #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM |character | #' |PERSON_ID |character | #' |PLAYER |character | #' |SEASON_TYPE |character | #' |ACTIVE_WITH_TEAM |character | #' |GP |character | #' |MINUTES |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |PF |character | #' |STL |character | #' |TOV |character | #' |BLK |character | #' |PTS |character | #' |F_RANK_GP |character | #' |F_RANK_MINUTES |character | #' |F_RANK_FGM |character | #' |F_RANK_FGA |character | #' |F_RANK_FG_PCT |character | #' |F_RANK_FG3M |character | #' |F_RANK_FG3A |character | #' |F_RANK_FG3_PCT |character | #' |F_RANK_FTM |character | #' |F_RANK_FTA |character | #' |F_RANK_FT_PCT |character | #' |F_RANK_OREB |character | #' |F_RANK_DREB |character | #' |F_RANK_REB |character | #' |F_RANK_AST |character | #' |F_RANK_PF |character | #' |F_RANK_STL |character | #' |F_RANK_TOV |character | #' |F_RANK_BLK |character | #' |F_RANK_PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Franchise Functions #' @details #' [Franchise Leaders](https://stats.wnba.com/team/1611661324/franchise-leaders) #' ```r #' wnba_franchiseleaderswrank(league_id = '10', team_id = '1611661324') #' ``` wnba_franchiseleaderswrank <- function( league_id = '10', per_mode = 'Totals', season_type = 'Regular Season', team_id = '1611661324', ...){ # season_type <- gsub(' ','+',season_type) version <- "franchiseleaderswrank" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no franchise players data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Franchise Players** #' @name wnba_franchiseplayers NULL #' @title #' **Get WNBA Stats API Franchise Players** #' @rdname wnba_franchiseplayers #' @author Saiem Gilani #' @param league_id league_id #' @param per_mode per_mode #' @param season_type season_type #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: FranchisePlayers #' #' **FranchisePlayers** #' #' #' |col_name |types | #' |:----------------|:---------| #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM |character | #' |PERSON_ID |character | #' |PLAYER |character | #' |SEASON_TYPE |character | #' |ACTIVE_WITH_TEAM |character | #' |GP |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |PF |character | #' |STL |character | #' |TOV |character | #' |BLK |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Franchise Functions #' @details #' [Franchise Players](https://stats.wnba.com/team/1611661319/franchise-leaders/) #' ```r #' wnba_franchiseplayers(league_id = '10', team_id = '1611661319') #' wnba_franchiseplayers(league_id = '10', season_type = 'Playoffs', team_id = '1611661319') #' ``` wnba_franchiseplayers <- function( league_id = '10', per_mode = 'Totals', season_type = 'Regular Season', team_id = '1611661319', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "franchiseplayers" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no franchise players data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Franchise History** #' @name wnba_franchisehistory NULL #' @title #' **Get WNBA Stats API Franchise History** #' @rdname wnba_franchisehistory #' @author Saiem Gilani #' @param league_id league_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: DefunctTeams, FranchiseHistory #' #' **FranchiseHistory** #' #' #' |col_name |types | #' |:--------------|:---------| #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |START_YEAR |character | #' |END_YEAR |character | #' |YEARS |character | #' |GAMES |character | #' |WINS |character | #' |LOSSES |character | #' |WIN_PCT |character | #' |PO_APPEARANCES |character | #' |DIV_TITLES |character | #' |CONF_TITLES |character | #' |LEAGUE_TITLES |character | #' #' **DefunctTeams** #' #' #' |col_name |types | #' |:--------------|:---------| #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |START_YEAR |character | #' |END_YEAR |character | #' |YEARS |character | #' |GAMES |character | #' |WINS |character | #' |LOSSES |character | #' |WIN_PCT |character | #' |PO_APPEARANCES |character | #' |DIV_TITLES |character | #' |CONF_TITLES |character | #' |LEAGUE_TITLES |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Franchise Functions #' @details #' [Franchise History](https://stats.wnba.com/history/) #' ```r #' wnba_franchisehistory(league_id = '10') #' ``` wnba_franchisehistory <- function( league_id = '10', ...){ version <- "franchisehistory" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no franchise history data available for {team_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_franchise.R
#' **Get WNBA Stats API League Hustle Stats Player** #' @name wnba_leaguehustlestatsplayer NULL #' @title #' **Get WNBA Stats API League Hustle Stats Player** #' @rdname wnba_leaguehustlestatsplayer #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param player_experience player_experience #' @param player_position player_position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: HustleStatsPlayer #' #' **HustleStatsPlayer** #' #' #' |col_name |types | #' |:-----------------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |G |character | #' |MIN |character | #' |CONTESTED_SHOTS |character | #' |CONTESTED_SHOTS_2PT |character | #' |CONTESTED_SHOTS_3PT |character | #' |DEFLECTIONS |character | #' |CHARGES_DRAWN |character | #' |SCREEN_ASSISTS |character | #' |SCREEN_AST_PTS |character | #' |OFF_LOOSE_BALLS_RECOVERED |character | #' |DEF_LOOSE_BALLS_RECOVERED |character | #' |LOOSE_BALLS_RECOVERED |character | #' |PCT_LOOSE_BALLS_RECOVERED_OFF |character | #' |PCT_LOOSE_BALLS_RECOVERED_DEF |character | #' |OFF_BOXOUTS |character | #' |DEF_BOXOUTS |character | #' |BOX_OUT_PLAYER_TEAM_REBS |character | #' |BOX_OUT_PLAYER_REBS |character | #' |BOX_OUTS |character | #' |PCT_BOX_OUTS_OFF |character | #' |PCT_BOX_OUTS_DEF |character | #' |PCT_BOX_OUTS_TEAM_REB |character | #' |PCT_BOX_OUTS_REB |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Hustle Functions #' @details #' ```r #' wnba_leaguehustlestatsplayer(league_id = '10') #' wnba_leaguehustlestatsplayer(league_id = '10', team_id = '1611661324') #' ``` wnba_leaguehustlestatsplayer <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', height = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', player_experience = '', player_position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', weight = '', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "leaguehustlestatsplayer" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, Height = height, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, PlayerExperience = player_experience, PlayerPosition = player_position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league hustle player stats data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Hustle Stats Player Leaders** #' @name wnba_leaguehustlestatsplayerleaders NULL #' @title #' **Get WNBA Stats API League Hustle Stats Player Leaders** #' @rdname wnba_leaguehustlestatsplayerleaders #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param player_experience player_experience #' @param player_position player_position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: PlayerChargesDrawnLeaders, #' PlayerContestedShotsLeaders, PlayerDeflectionsLeaders, PlayerLooseBallLeaders, #' PlayerScreenAssistLeaders, Table5 #' #' **PlayerContestedShotsLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |CONTESTED_SHOTS |character | #' #' **PlayerChargesDrawnLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |CHARGES_DRAWN |character | #' #' **PlayerDeflectionsLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |DEFLECTIONS |character | #' #' **PlayerLooseBallLeaders** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |LOOSE_BALLS_RECOVERED |character | #' #' **PlayerScreenAssistLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |SCREEN_ASSISTS |character | #' #' **Table5** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |RANK |character | #' |BOX_OUTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Hustle Functions #' @details #' ```r #' wnba_leaguehustlestatsplayerleaders(league_id = '10') #' ``` wnba_leaguehustlestatsplayerleaders <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', height = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', player_experience = '', player_position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', weight = '', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "leaguehustlestatsplayerleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, Height = height, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, PlayerExperience = player_experience, PlayerPosition = player_position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league hustle stats player leaders data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Hustle Stats Team** #' @name wnba_leaguehustlestatsteam NULL #' @title #' **Get WNBA Stats API League Hustle Stats Team** #' @rdname wnba_leaguehustlestatsteam #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param player_experience player_experience #' @param player_position player_position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: HustleStatsTeam #' #' **HustleStatsTeam** #' #' #' |col_name |types | #' |:-----------------------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |MIN |character | #' |CONTESTED_SHOTS |character | #' |CONTESTED_SHOTS_2PT |character | #' |CONTESTED_SHOTS_3PT |character | #' |DEFLECTIONS |character | #' |CHARGES_DRAWN |character | #' |SCREEN_ASSISTS |character | #' |SCREEN_AST_PTS |character | #' |OFF_LOOSE_BALLS_RECOVERED |character | #' |DEF_LOOSE_BALLS_RECOVERED |character | #' |LOOSE_BALLS_RECOVERED |character | #' |PCT_LOOSE_BALLS_RECOVERED_OFF |character | #' |PCT_LOOSE_BALLS_RECOVERED_DEF |character | #' |OFF_BOXOUTS |character | #' |DEF_BOXOUTS |character | #' |BOX_OUTS |character | #' |PCT_BOX_OUTS_OFF |character | #' |PCT_BOX_OUTS_DEF |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Hustle Functions #' @details #' ```r #' wnba_leaguehustlestatsteam(league_id = '10') #' ``` wnba_leaguehustlestatsteam <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', height = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', player_experience = '', player_position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', weight = '', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "leaguehustlestatsteam" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, Height = height, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, PlayerExperience = player_experience, PlayerPosition = player_position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league hustle team stats data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Hustle Stats Team Leaders** #' @name wnba_leaguehustlestatsteamleaders NULL #' @title #' **Get WNBA Stats API League Hustle Stats Team Leaders** #' @rdname wnba_leaguehustlestatsteamleaders #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param player_experience player_experience #' @param player_position player_position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Table5, Table6, TeamChargesDrawnLeaders, #' TeamContestedShotsLeaders, TeamDeflectionsLeaders, #' TeamLooseBallLeaders, TeamScreenAssistLeaders #' #' **TeamContestedShotsLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |CONTESTED_SHOTS |character | #' #' **TeamChargesDrawnLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |CHARGES_DRAWN |character | #' #' **TeamDeflectionsLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |DEFLECTIONS |character | #' #' **TeamLooseBallLeaders** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |LOOSE_BALLS_RECOVERED |character | #' #' **TeamScreenAssistLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |SCREEN_ASSISTS |character | #' #' **Table5** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |BOX_OUTS |character | #' #' **Table6** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |RANK |character | #' |BOX_OUTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Hustle Functions #' @details #' ```r #' wnba_leaguehustlestatsteamleaders(league_id = '10') #' ``` wnba_leaguehustlestatsteamleaders <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', height = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', player_experience = '', player_position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', weight = '', ...){ # intentional # season_type <- gsub(' ','+',season_type) version <- "leaguehustlestatsteamleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, Height = height, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, PlayerExperience = player_experience, PlayerPosition = player_position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league hustle team stats leaders data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_hustle.R
#' **Get WNBA Stats API All-time Leaders Grid** #' @name wnba_alltimeleadersgrids NULL #' @title #' **Get WNBA Stats API All-time Leaders Grid** #' @rdname wnba_alltimeleadersgrids #' @author Saiem Gilani #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param per_mode Per Mode - PerGame, Totals #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param top_x Top X #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: ASTLeaders, BLKLeaders, DREBLeaders, #' FG3ALeaders, FG3MLeaders, FG3_PCTLeaders, FGALeaders, FGMLeaders, #' FG_PCTLeaders, FTALeaders, FTMLeaders, FT_PCTLeaders, GPLeaders, #' OREBLeaders, PFLeaders, PTSLeaders, REBLeaders, STLLeaders, TOVLeaders #' #' **GPLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |GP |character | #' |GP_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **PTSLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |PTS |character | #' |PTS_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **ASTLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |AST |character | #' |AST_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **STLLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |STL |character | #' |STL_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **OREBLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |OREB |character | #' |OREB_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **DREBLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |DREB |character | #' |DREB_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **REBLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |REB |character | #' |REB_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **BLKLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |BLK |character | #' |BLK_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FGMLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGM |character | #' |FGM_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FGALeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGA |character | #' |FGA_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FG_PCTLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FG_PCT |character | #' |FG_PCT_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **TOVLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TOV |character | #' |TOV_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FG3MLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FG3M |character | #' |FG3M_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FG3ALeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FG3A |character | #' |FG3A_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FG3_PCTLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FG3_PCT |character | #' |FG3_PCT_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **PFLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |PF |character | #' |PF_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FTMLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FTM |character | #' |FTM_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FTALeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FTA |character | #' |FTA_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' **FT_PCTLeaders** #' #' #' |col_name |types | #' |:--------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FT_PCT |character | #' |FT_PCT_RANK |character | #' |IS_ACTIVE_FLAG |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_alltimeleadersgrids(league_id = '10') #' ``` wnba_alltimeleadersgrids <- function( league_id = '10', per_mode = 'PerGame', season_type = 'Regular Season', top_x = 10, ...){ # intentional # season_type <- gsub(' ', '+', season_type) version <- "alltimeleadersgrids" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, SeasonType = season_type, TopX = top_x ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no all-time leaders grid data for {league_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Assist Leaders** #' @name wnba_assistleaders NULL #' @title #' **Get WNBA Stats API Assist Leaders** #' @rdname wnba_assistleaders #' @author Saiem Gilani #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param per_mode Per Mode - PerGame, Totals #' @param player_or_team Player or Team #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: AssistLeaders #' #' **AssistLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |PLAYER_ID |character | #' |PLAYER |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |JERSEY_NUM |character | #' |PLAYER_POSITION |character | #' |AST |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_assistleaders(league_id = '10', player_or_team = "Player") #' wnba_assistleaders(league_id = '10', player_or_team = "Team") #' ``` wnba_assistleaders <- function( league_id = '10', per_mode = 'PerGame', player_or_team = 'Team', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "assistleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, PlayerOrTeam = player_or_team, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no assist leaders data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Assist Tracker** #' @name wnba_assisttracker NULL #' @title #' **Get WNBA Stats API Assist Tracker** #' @rdname wnba_assisttracker #' @author Saiem Gilani #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param per_mode Per Mode - PerGame, Totals #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: AssistTracker #' #' **AssistTracker** #' #' |col_name |types | #' |:--------|:-------| #' |ASSISTS |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_assisttracker(league_id = '10') #' ``` wnba_assisttracker <- function( league_id = '10', per_mode = 'PerGame', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "assisttracker" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, Season = season, SeasonType = season_type) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no assist tracker data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Homepage Leaders** #' @name wnba_homepageleaders NULL #' @title #' **Get WNBA Stats API Homepage Leaders** #' @rdname wnba_homepageleaders #' @author Saiem Gilani #' @param game_scope Game Scope - Season, Last 10, ,Yesterday, Finals #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs #' @param player_or_team Player or Team #' @param player_scope Player Scope - All Players, Rookies #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param stat_category Stat Category: Points, Rebounds, Assists, Defense, Clutch, Playmaking, Efficiency, Fast Break, Scoring Breakdown #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: HomePageLeaders, LeagueAverage, LeagueMax #' #' **HomePageLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |PLAYERID |character | #' |PLAYER |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |PTS |character | #' |FG_PCT |character | #' |FG3_PCT |character | #' |FT_PCT |character | #' |EFG_PCT |character | #' |TS_PCT |character | #' |PTS_PER48 |character | #' #' **LeagueAverage** #' #' #' |col_name |types | #' |:---------|:-------| #' |PTS |numeric | #' |FG_PCT |numeric | #' |FG3_PCT |numeric | #' |FT_PCT |numeric | #' |EFG_PCT |numeric | #' |TS_PCT |numeric | #' |PTS_PER48 |numeric | #' #' **LeagueMax** #' #' #' |col_name |types | #' |:---------|:-------| #' |PTS |numeric | #' |FG_PCT |numeric | #' |FG3_PCT |numeric | #' |FT_PCT |numeric | #' |EFG_PCT |numeric | #' |TS_PCT |numeric | #' |PTS_PER48 |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_homepageleaders(league_id = '10', player_or_team = "Player") #' wnba_homepageleaders(league_id = '10', player_or_team = "Team") #' ``` wnba_homepageleaders <- function( league_id = '10', game_scope = 'Season', player_or_team = 'Team', player_scope = 'All Players', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', stat_category = 'Points', ...){ player_scope <- gsub(' ','+',player_scope) # Intentional # season_type <- gsub(' ','+',season_type) stat_category <- gsub(' ','+',stat_category) version <- "homepageleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameScope = game_scope, LeagueID = league_id, PlayerOrTeam = player_or_team, PlayerScope = player_scope, Season = season, SeasonType = season_type, StatCategory = stat_category ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no homepage leaders data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API HomepageV2 Leaders** #' @name wnba_homepagev2 NULL #' @title #' **Get WNBA Stats API HomepageV2 Leaders** #' @rdname wnba_homepagev2 #' @author Saiem Gilani #' @param game_scope Game Scope - Season, Last 10, ,Yesterday, Finals #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs #' @param player_or_team Player or Team #' @param player_scope Player Scope - All Players, Rookies #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param stat_type Stat Type - Traditional, Advanced, Tracking #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: HomePageStat1, HomePageStat2, HomePageStat3, #' HomePageStat4, HomePageStat5, HomePageStat6, HomePageStat7, HomePageStat8 #' #' **HomePageStat1** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |PTS |character | #' #' **HomePageStat2** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |REB |character | #' #' **HomePageStat3** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |AST |character | #' #' **HomePageStat4** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |STL |character | #' #' **HomePageStat5** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |FG_PCT |character | #' #' **HomePageStat6** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |FT_PCT |character | #' #' **HomePageStat7** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |FG3_PCT |character | #' #' **HomePageStat8** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |BLK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_homepagev2(league_id = '10', player_or_team = "Player") #' wnba_homepagev2(league_id = '10', player_or_team = "Team") #' ``` wnba_homepagev2 <- function( league_id = '10', game_scope = 'Season', player_or_team = 'Team', player_scope = 'All Players', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', stat_type = 'Traditional', ...){ player_scope <- gsub(' ','+',player_scope) # Intentional # season_type <- gsub(' ','+',season_type) stat_type <- gsub(' ','+',stat_type) version <- "homepagev2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameScope = game_scope, LeagueID = league_id, PlayerOrTeam = player_or_team, PlayerScope = player_scope, Season = season, SeasonType = season_type, StatType = stat_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no homepage v2 data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Leaders Tiles** #' @name wnba_leaderstiles NULL #' @title #' **Get WNBA Stats API Leaders Tiles** #' @rdname wnba_leaderstiles #' @author Saiem Gilani #' @param game_scope Game Scope - Season, Last 10, ,Yesterday, Finals #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs #' @param player_or_team Player or Team #' @param player_scope Player Scope - All Players, Rookies #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param stat Stat - PTS, REB, AST, FG_PCT, FT_PCT, FG3_PCT, STL, BLK #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: AllTimeSeasonHigh, LastSeasonHigh, #' LeadersTiles, LowSeasonHigh, #' #' **LeadersTiles** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |PTS |character | #' #' **AllTimeSeasonHigh** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |SEASON_YEAR |character | #' |PTS |character | #' #' **LastSeasonHigh** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |RANK |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |PTS |character | #' #' **LowSeasonHigh** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |SEASON_YEAR |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_leaderstiles(league_id = '10', player_or_team = "Player") #' wnba_leaderstiles(league_id = '10', player_or_team = "Team") #' ``` wnba_leaderstiles <- function( league_id = '10', game_scope = 'Season', player_or_team = 'Team', player_scope = 'All Players', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', stat = 'PTS', ...){ player_scope <- gsub(' ','+',player_scope) # season_type <- gsub(' ','+',season_type) stat <- gsub(' ','+',stat) version <- "leaderstiles" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameScope = game_scope, LeagueID = league_id, PlayerOrTeam = player_or_team, PlayerScope = player_scope, Season = season, SeasonType = season_type, Stat = stat ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no leaders tiles data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Leaders** #' @name wnba_leagueleaders NULL #' @title #' **Get WNBA Stats API League Leaders** #' @rdname wnba_leagueleaders #' @author Saiem Gilani #' @param active_flag Active Flag #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs #' @param per_mode Per Mode - Totals, PerGame, Per48 #' @param scope Scope - RS, S, Rookies #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param stat_category Stat Category: PTS, REB, AST, FG_PCT, FT_PCT, FG3_PCT, STL, BLK #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueLeaders #' #' **LeagueLeaders** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |RANK |character | #' |PLAYER |character | #' |TEAM_ID |character | #' |TEAM |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' |EFF |character | #' |AST_TOV |character | #' |STL_TOV |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Leaders Functions #' @details #' ```r #' wnba_leagueleaders(league_id = '10') #' ``` wnba_leagueleaders <- function( active_flag = '', league_id = '10', per_mode = 'Totals', scope = 'S', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', stat_category = 'PTS', ...){ scope <- gsub(' ','+',scope) # season_type <- gsub(' ','+',season_type) stat_category <- gsub(' ','+',stat_category) version <- "leagueleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( ActiveFlag = active_flag, LeagueID = league_id, PerMode = per_mode, Scope = scope, Season = season, SeasonType = season_type, StatCategory = stat_category ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSet$name), function(x){ data <- resp$resultSet$rowSet %>% data.frame(stringsAsFactors = F) %>% dplyr::as_tibble() json_names <- resp$resultSet$headers colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSet$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league leaders data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } # #' **Get WNBA Stats API Defense Hub** # #' @name wnba_defensehub # NULL # #' @title # #' **Get WNBA Stats API Defense Hub** # #' @rdname wnba_defensehub # #' @author Saiem Gilani # #' @param game_scope Game Scope - Season, Last 10, ,Yesterday, Finals # #' @param season Season - format 2020-21 # #' @param season_type Season Type - Regular Season, Playoffs # #' @param player_or_team Player or Team # #' @param player_scope Player Scope - All Players, Rookies # #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League # #' @param ... Additional arguments passed to an underlying function like httr. # #' @return Returns a named list of data frames: DefenseHubStat1, DefenseHubStat10, DefenseHubStat2, DefenseHubStat3, DefenseHubStat4, DefenseHubStat5, DefenseHubStat6, # #' DefenseHubStat7, DefenseHubStat8, DefenseHubStat9 # #' @importFrom jsonlite fromJSON toJSON # #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble # #' @import rvest # #' @export # #' @family WNBA Leaders Functions # #' @details # #' (Possibly Deprecated) # #' ```r # #' wnba_defensehub(league_id = '10', player_or_team = "Player") # #' wnba_defensehub(league_id = '10', player_or_team = "Team") # #' ``` # # wnba_defensehub <- function( # league_id = '10', # game_scope = 'Season', # player_or_team = 'Team', # player_scope = 'All Players', # season = most_recent_wnba_season() - 1, # season_type = 'Regular Season', # ...){ # # player_scope <- gsub(' ','+',player_scope) # # season_type <- gsub(' ','+',season_type) # version <- "defensehub" # endpoint <- wnba_endpoint(version) # full_url <- endpoint # # params <- list( # GameScope = game_scope, # LeagueID = league_id, # PlayerOrTeam = player_or_team, # PlayerScope = player_scope, # Season = season, # SeasonType = season_type # ) # # tryCatch( # expr = { # # resp <- request_with_proxy(url = full_url, params = params, ...) # # df_list <- wnba_stats_map_result_sets(resp) # # }, # error = function(e) { # message(glue::glue("{Sys.time()}: Invalid arguments or no defense hub data for {season} available!")) # }, # warning = function(w) { # }, # finally = { # } # ) # return(df_list) # }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_leaders.R
#' **Get WNBA Stats API League Game Log** #' @name wnba_leaguegamelog NULL #' @title #' **Get WNBA Stats API League Game Log** #' @rdname wnba_leaguegamelog #' @author Saiem Gilani #' @param counter counter #' @param date_from date_from #' @param date_to date_to #' @param direction direction #' @param league_id league_id #' @param player_or_team player_or_team #' @param season season #' @param season_type season_type #' @param sorter sorter #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: LeagueGameLog #' #' **LeagueGameLog** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |SEASON_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |VIDEO_AVAILABLE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @details #' [Player/Team Boxscores](https://stats.wnba.com/players/boxscores-traditional/) #' ```r #' wnba_leaguegamelog(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguegamelog <- function( counter = 0, date_from = '', date_to = '', direction = 'ASC', league_id = '00', player_or_team = 'T', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', sorter = 'DATE', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguegamelog" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Counter = counter, DateFrom = date_from, DateTo = date_to, Direction = direction, LeagueID = league_id, PlayerOrTeam = player_or_team, Season = season, SeasonType = season_type, Sorter = sorter ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league game log data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Standings V3** #' @name wnba_leaguestandingsv3 NULL #' @title #' **Get WNBA Stats API League Standings V3** #' @rdname wnba_leaguestandingsv3 #' @author Saiem Gilani #' @param league_id league_id #' @param season season #' @param season_type season_type #' @param season_year season_year #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Standings #' #' **Standings** #' #' #' |col_name |types | #' |:-----------------------|:---------| #' |LeagueID |character | #' |SeasonID |character | #' |TeamID |character | #' |TeamCity |character | #' |TeamName |character | #' |TeamSlug |character | #' |Conference |character | #' |ConferenceRecord |character | #' |PlayoffRank |character | #' |ClinchIndicator |character | #' |Division |character | #' |DivisionRecord |character | #' |DivisionRank |character | #' |WINS |character | #' |LOSSES |character | #' |WinPCT |character | #' |LeagueRank |character | #' |Record |character | #' |HOME |character | #' |ROAD |character | #' |L10 |character | #' |Last10Home |character | #' |Last10Road |character | #' |OT |character | #' |ThreePTSOrLess |character | #' |TenPTSOrMore |character | #' |LongHomeStreak |character | #' |strLongHomeStreak |character | #' |LongRoadStreak |character | #' |strLongRoadStreak |character | #' |LongWinStreak |character | #' |LongLossStreak |character | #' |CurrentHomeStreak |character | #' |strCurrentHomeStreak |character | #' |CurrentRoadStreak |character | #' |strCurrentRoadStreak |character | #' |CurrentStreak |character | #' |strCurrentStreak |character | #' |ConferenceGamesBack |character | #' |DivisionGamesBack |character | #' |ClinchedConferenceTitle |character | #' |ClinchedDivisionTitle |character | #' |ClinchedPlayoffBirth |character | #' |ClinchedPlayIn |character | #' |EliminatedConference |character | #' |EliminatedDivision |character | #' |AheadAtHalf |character | #' |BehindAtHalf |character | #' |TiedAtHalf |character | #' |AheadAtThird |character | #' |BehindAtThird |character | #' |TiedAtThird |character | #' |Score100PTS |character | #' |OppScore100PTS |character | #' |OppOver500 |character | #' |LeadInFGPCT |character | #' |LeadInReb |character | #' |FewerTurnovers |character | #' |PointsPG |character | #' |OppPointsPG |character | #' |DiffPointsPG |character | #' |vsEast |character | #' |vsAtlantic |character | #' |vsCentral |character | #' |vsSoutheast |character | #' |vsWest |character | #' |vsNorthwest |character | #' |vsPacific |character | #' |vsSouthwest |character | #' |Jan |character | #' |Feb |character | #' |Mar |character | #' |Apr |character | #' |May |character | #' |Jun |character | #' |Jul |character | #' |Aug |character | #' |Sep |character | #' |Oct |character | #' |Nov |character | #' |Dec |character | #' |Score_80_Plus |character | #' |Opp_Score_80_Plus |character | #' |Score_Below_80 |character | #' |Opp_Score_Below_80 |character | #' |TotalPoints |character | #' |OppTotalPoints |character | #' |DiffTotalPoints |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @details #' [League Standings](https://www.wnba.com/standings/#?season=2022) #' ```r #' wnba_leaguestandingsv3(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguestandingsv3 <- function( league_id = '10', season = most_recent_wnba_season(), season_type = 'Regular Season', season_year = '', ...){ # Intentional # season_type <- gsub(' ','+',season_type) version <- "leaguestandingsv3" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, SeasonType = season_type, SeasonYear = season_year ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league standings v3 data available for {season}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Game Streak Finder** #' @name wnba_leaguegamefinder NULL #' @title #' **Get WNBA Stats API League Game Streak Finder** #' @rdname wnba_leaguegamefinder #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_year draft_year #' @param draft_team_id draft_team_id #' @param draft_round draft_round #' @param draft_number draft_number #' @param et_ast et_ast #' @param et_blk et_blk #' @param et_dd et_dd #' @param et_dreb et_dreb #' @param et_fg3a et_fg3a #' @param et_fg3m et_fg3m #' @param et_fg3_pct et_fg3_pct #' @param et_fga et_fga #' @param et_fgm et_fgm #' @param et_fg_pct et_fg_pct #' @param et_fta et_fta #' @param et_ftm et_ftm #' @param et_ft_pct et_ft_pct #' @param et_minutes et_minutes #' @param et_oreb et_oreb #' @param et_pf et_pf #' @param et_pts et_pts #' @param et_reb et_reb #' @param et_stl et_stl #' @param et_td et_td #' @param et_tov et_tov #' @param game_id game_id #' @param gt_ast gt_ast #' @param gt_blk gt_blk #' @param gt_dd gt_dd #' @param gt_dreb gt_dreb #' @param gt_fg3a gt_fg3a #' @param gt_fg3m gt_fg3m #' @param gt_fg3_pct gt_fg3_pct #' @param gt_fga gt_fga #' @param gt_fgm gt_fgm #' @param gt_fg_pct gt_fg_pct #' @param gt_fta gt_fta #' @param gt_ftm gt_ftm #' @param gt_ft_pct gt_ft_pct #' @param gt_minutes gt_minutes #' @param gt_oreb gt_oreb #' @param gt_pf gt_pf #' @param gt_pts gt_pts #' @param gt_reb gt_reb #' @param gt_stl gt_stl #' @param gt_td gt_td #' @param gt_tov gt_tov #' @param league_id league_id #' @param location location #' @param lt_ast lt_ast #' @param lt_blk lt_blk #' @param lt_dd lt_dd #' @param lt_dreb lt_dreb #' @param lt_fg3a lt_fg3a #' @param lt_fg3m lt_fg3m #' @param lt_fg3_pct lt_fg3_pct #' @param lt_fga lt_fga #' @param lt_fgm lt_fgm #' @param lt_fg_pct lt_fg_pct #' @param lt_fta lt_fta #' @param lt_ftm lt_ftm #' @param lt_ft_pct lt_ft_pct #' @param lt_minutes lt_minutes #' @param lt_oreb lt_oreb #' @param lt_pf lt_pf #' @param lt_pts lt_pts #' @param lt_reb lt_reb #' @param lt_stl lt_stl #' @param lt_td lt_td #' @param lt_tov lt_tov #' @param outcome outcome #' @param po_round po_round #' @param player_or_team player_or_team #' @param player_id player_id #' @param rookie_year rookie_year #' @param season season - Min: '1983-84' #' @param season_segment season_segment #' @param season_type season_type #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_team_id vs_team_id #' @param years_experience years_experience #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: LeagueGameFinderResults #' #' **LeagueGameFinderResults** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |SEASON_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |MIN |character | #' |PTS |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PLUS_MINUS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Game Finder Functions #' @details #' ```r #' wnba_leaguegamefinder(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguegamefinder <- function( conference = '', date_from = '', date_to = '', division = '', draft_year = '', draft_team_id = '', draft_round = '', draft_number = '', et_ast = '', et_blk = '', et_dd = '', et_dreb = '', et_fg3a = '', et_fg3m = '', et_fg3_pct = '', et_fga = '', et_fgm = '', et_fg_pct = '', et_fta = '', et_ftm = '', et_ft_pct = '', et_minutes = '', et_oreb = '', et_pf = '', et_pts = '', et_reb = '', et_stl = '', et_td = '', et_tov = '', game_id = '', gt_ast = '', gt_blk = '', gt_dd = '', gt_dreb = '', gt_fg3a = '', gt_fg3m = '', gt_fg3_pct = '', gt_fga = '', gt_fgm = '', gt_fg_pct = '', gt_fta = '', gt_ftm = '', gt_ft_pct = '', gt_minutes = '', gt_oreb = '', gt_pf = '', gt_pts = '', gt_reb = '', gt_stl = '', gt_td = '', gt_tov = '', league_id = '10', location = '', lt_ast = '', lt_blk = '', lt_dd = '', lt_dreb = '', lt_fg3a = '', lt_fg3m = '', lt_fg3_pct = '', lt_fga = '', lt_fgm = '', lt_fg_pct = '', lt_fta = '', lt_ftm = '', lt_ft_pct = '', lt_minutes = '', lt_oreb = '', lt_pf = '', lt_pts = '', lt_reb = '', lt_stl = '', lt_td = '', lt_tov = '', outcome = '', po_round = '', player_id = '', player_or_team = 'T', rookie_year = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', starter_bench = '', team_id = '', vs_conference = '', vs_division = '', vs_team_id = '', years_experience = '', ...){ # season_type <- gsub(' ','+',season_type) version <- "leaguegamefinder" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, DraftNumber = draft_number, DraftRound = draft_round, DraftTeamID = draft_team_id, DraftYear = draft_year, EqAST = et_ast, EqBLK = et_blk, EqDD = et_dd, EqDREB = et_dreb, EqFG3A = et_fg3a, EqFG3M = et_fg3m, EqFG3_PCT = et_fg3_pct, EqFGA = et_fga, EqFGM = et_fgm, EqFG_PCT = et_fg_pct, EqFTA = et_fta, EqFTM = et_ftm, EqFT_PCT = et_ft_pct, EqMINUTES = et_minutes, EqOREB = et_oreb, EqPF = et_pf, EqPTS = et_pts, EqREB = et_reb, EqSTL = et_stl, EqTD = et_td, EqTOV = et_tov, GameID = game_id, GtAST = gt_ast, GtBLK = gt_blk, GtDD = gt_dd, GtDREB = gt_dreb, GtFG3A = gt_fg3a, GtFG3M = gt_fg3m, GtFG3_PCT = gt_fg3_pct, GtFGA = gt_fga, GtFGM = gt_fgm, GtFG_PCT = gt_fg_pct, GtFTA = gt_fta, GtFTM = gt_ftm, GtFT_PCT = gt_ft_pct, GtMINUTES = gt_minutes, GtOREB = gt_oreb, GtPF = gt_pf, GtPTS = gt_pts, GtREB = gt_reb, GtSTL = gt_stl, GtTD = gt_td, GtTOV = gt_tov, LeagueID = league_id, Location = location, LtAST = lt_ast, LtBLK = lt_blk, LtDD = lt_dd, LtDREB = lt_dreb, LtFG3A = lt_fg3a, LtFG3M = lt_fg3m, LtFG3_PCT = lt_fg3_pct, LtFGA = lt_fga, LtFGM = lt_fgm, LtFG_PCT = lt_fg_pct, LtFTA = lt_fta, LtFTM = lt_ftm, LtFT_PCT = lt_ft_pct, LtMINUTES = lt_minutes, LtOREB = lt_oreb, LtPF = lt_pf, LtPTS = lt_pts, LtREB = lt_reb, LtSTL = lt_stl, LtTD = lt_td, LtTOV = lt_tov, Outcome = outcome, PORound = po_round, PlayerID = player_id, PlayerOrTeam = player_or_team, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsTeamID = vs_team_id, YearsExperience = years_experience ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league game finder data available for the given parameters!")) }, warning = function(w) { }, finally = { } ) return(df_list) } ## wnba_playoffpicture # #' **Get WNBA Stats API Playoff Picture** # #' @name wnba_playoffpicture # NULL # #' @title # #' **Get WNBA Stats API Playoff Picture** # #' @rdname wnba_playoffpicture # #' @author Saiem Gilani # #' @param league_id league_id # #' @param season_id season_id # #' @param ... Additional arguments passed to an underlying function like httr. # #' @return Return a named list of data frames: EastConfPlayoffPicture, # #' EastConfRemainingGames, EastConfStandings, WestConfPlayoffPicture, # #' WestConfRemainingGames, WestConfStandings # #' # #' **EastConfPlayoffPicture** # #' # #' # #' |col_name |types | # #' |:---------------------------------|:---------| # #' |CONFERENCE |character | # #' |HIGH_SEED_RANK |character | # #' |HIGH_SEED_TEAM |character | # #' |HIGH_SEED_TEAM_ID |character | # #' |LOW_SEED_RANK |character | # #' |LOW_SEED_TEAM |character | # #' |LOW_SEED_TEAM_ID |character | # #' |HIGH_SEED_SERIES_W |character | # #' |HIGH_SEED_SERIES_L |character | # #' |HIGH_SEED_SERIES_REMAINING_G |character | # #' |HIGH_SEED_SERIES_REMAINING_HOME_G |character | # #' |HIGH_SEED_SERIES_REMAINING_AWAY_G |character | # #' # #' **WestConfPlayoffPicture** # #' # #' # #' |col_name |types | # #' |:---------------------------------|:---------| # #' |CONFERENCE |character | # #' |HIGH_SEED_RANK |character | # #' |HIGH_SEED_TEAM |character | # #' |HIGH_SEED_TEAM_ID |character | # #' |LOW_SEED_RANK |character | # #' |LOW_SEED_TEAM |character | # #' |LOW_SEED_TEAM_ID |character | # #' |HIGH_SEED_SERIES_W |character | # #' |HIGH_SEED_SERIES_L |character | # #' |HIGH_SEED_SERIES_REMAINING_G |character | # #' |HIGH_SEED_SERIES_REMAINING_HOME_G |character | # #' |HIGH_SEED_SERIES_REMAINING_AWAY_G |character | # #' # #' **EastConfStandings** # #' # #' # #' |col_name |types | # #' |:-------------------|:---------| # #' |CONFERENCE |character | # #' |RANK |character | # #' |TEAM |character | # #' |TEAM_SLUG |character | # #' |TEAM_ID |character | # #' |WINS |character | # #' |LOSSES |character | # #' |PCT |character | # #' |DIV |character | # #' |CONF |character | # #' |HOME |character | # #' |AWAY |character | # #' |GB |character | # #' |GR_OVER_500 |character | # #' |GR_OVER_500_HOME |character | # #' |GR_OVER_500_AWAY |character | # #' |GR_UNDER_500 |character | # #' |GR_UNDER_500_HOME |character | # #' |GR_UNDER_500_AWAY |character | # #' |RANKING_CRITERIA |character | # #' |CLINCHED_PLAYOFFS |character | # #' |CLINCHED_CONFERENCE |character | # #' |CLINCHED_DIVISION |character | # #' |ELIMINATED_PLAYOFFS |character | # #' |SOSA_REMAINING |character | # #' # #' **WestConfStandings** # #' # #' # #' |col_name |types | # #' |:-------------------|:---------| # #' |CONFERENCE |character | # #' |RANK |character | # #' |TEAM |character | # #' |TEAM_SLUG |character | # #' |TEAM_ID |character | # #' |WINS |character | # #' |LOSSES |character | # #' |PCT |character | # #' |DIV |character | # #' |CONF |character | # #' |HOME |character | # #' |AWAY |character | # #' |GB |character | # #' |GR_OVER_500 |character | # #' |GR_OVER_500_HOME |character | # #' |GR_OVER_500_AWAY |character | # #' |GR_UNDER_500 |character | # #' |GR_UNDER_500_HOME |character | # #' |GR_UNDER_500_AWAY |character | # #' |RANKING_CRITERIA |character | # #' |CLINCHED_PLAYOFFS |character | # #' |CLINCHED_CONFERENCE |character | # #' |CLINCHED_DIVISION |character | # #' |ELIMINATED_PLAYOFFS |character | # #' |SOSA_REMAINING |character | # #' # #' **EastConfRemainingGames** # #' # #' # #' |col_name |types | # #' |:----------------|:---------| # #' |TEAM |character | # #' |TEAM_ID |character | # #' |REMAINING_G |character | # #' |REMAINING_HOME_G |character | # #' |REMAINING_AWAY_G |character | # #' # #' **WestConfRemainingGames** # #' # #' # #' |col_name |types | # #' |:----------------|:---------| # #' |TEAM |character | # #' |TEAM_ID |character | # #' |REMAINING_G |character | # #' |REMAINING_HOME_G |character | # #' |REMAINING_AWAY_G |character | # #' # #' @importFrom jsonlite fromJSON toJSON # #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble # #' @import rvest # #' @export # #' @family WNBA League Functions # #' @details # #' ```r # #' wnba_playoffpicture(league_id = '10', season_id = paste0(2, most_recent_wnba_season())) # #' ``` # wnba_playoffpicture <- function( # league_id = '10', # season_id = '22022', # ...){ # # version <- "playoffpicture" # endpoint <- wnba_endpoint(version) # full_url <- endpoint # # params <- list( # LeagueID = league_id, # SeasonID = season_id # ) # # tryCatch( # expr = { # # resp <- request_with_proxy(url = full_url, params = params, ...) # # df_list <- wnba_stats_map_result_sets(resp) # # }, # error = function(e) { # message(glue::glue("{Sys.time()}: Invalid arguments or no playoff picture data available for {season}!")) # }, # warning = function(w) { # }, # finally = { # } # ) # return(df_list) # }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_league.R
#' **Get WNBA Stats API League Dashboard Player Biographical Stats** #' @name wnba_leaguedashplayerbiostats NULL #' @title #' **Get WNBA Stats API League Dashboard Player Biographical Stats** #' @rdname wnba_leaguedashplayerbiostats #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param game_segment game_segment #' @param game_scope game_scope #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param touch_time_range touch_time_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueDashPlayerBioStats #' #' **LeagueDashPlayerBioStats** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |PLAYER_HEIGHT |character | #' |PLAYER_HEIGHT_INCHES |character | #' |PLAYER_WEIGHT |character | #' |COLLEGE |character | #' |COUNTRY |character | #' |DRAFT_YEAR |character | #' |DRAFT_ROUND |character | #' |DRAFT_NUMBER |character | #' |GP |character | #' |PTS |character | #' |REB |character | #' |AST |character | #' |NET_RATING |character | #' |OREB_PCT |character | #' |DREB_PCT |character | #' |USG_PCT |character | #' |TS_PCT |character | #' |AST_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @details #' ```r #' wnba_leaguedashplayerbiostats(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashplayerbiostats <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', game_segment = '', game_scope = '', height = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', period = '', player_experience = '', player_position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', touch_time_range = '', vs_conference = '', vs_division = '', weight = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashplayerbiostats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, GameScope = game_scope, GameSegment = game_segment, Height = height, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, TouchTimeRange = touch_time_range, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard player bio stats data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard by Player Clutch Splits** #' @name wnba_leaguedashplayerclutch NULL #' @title #' **Get WNBA Stats API League Dashboard by Player Clutch Splits** #' @rdname wnba_leaguedashplayerclutch #' @author Saiem Gilani #' @param ahead_behind ahead_behind #' @param clutch_time clutch_time #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param game_scope game_scope #' @param game_segment game_segment #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param plus_minus plus_minus #' @param point_diff point_diff #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param touch_time_range touch_time_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueDashPlayerClutch #' #' **LeagueDashPlayerClutch** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @details #' ```r #' wnba_leaguedashplayerclutch(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashplayerclutch <- function( ahead_behind = 'Ahead or Behind', clutch_time = 'Last 5 Minutes', college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', game_scope = '', game_segment = '', height = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', point_diff = 5, po_round = '', per_mode = 'Totals', period = 0, player_experience = '', player_position = '', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', touch_time_range = '', vs_conference = '', vs_division = '', weight = '', ...){ # ahead_behind <- gsub(' ', '+', ahead_behind) # clutch_time <- gsub(' ', '+', clutch_time) # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashplayerclutch" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( AheadBehind = ahead_behind, ClutchTime = clutch_time, College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, GameScope = game_scope, GameSegment = game_segment, Height = height, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, PlusMinus = plus_minus, PointDiff = point_diff, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, TouchTimeRange = touch_time_range, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard player clutch stats data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard Player Stats** #' @name wnba_leaguedashplayerstats NULL #' @title #' **Get WNBA Stats API League Dashboard Player Stats** #' @rdname wnba_leaguedashplayerstats #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param game_scope game_scope #' @param game_segment game_segment #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param two_way two_way #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueDashPlayerStats #' #' **LeagueDashPlayerStats** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @details #' ```r #' wnba_leaguedashplayerstats(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashplayerstats <- function( college = '', conference = '', country = '', date_from = '', date_to = '', division = '', draft_pick = '', draft_year = '', game_scope = '', game_segment = '', height = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', po_round = '', per_mode = 'Totals', period = 0, player_experience = '', player_position = '', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', two_way = '', vs_conference = '', vs_division = '', weight = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashplayerstats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DraftPick = draft_pick, DraftYear = draft_year, GameScope = game_scope, GameSegment = game_segment, Height = height, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, TwoWay = two_way, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard player stats data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard Player Shot Locations** #' @name wnba_leaguedashplayershotlocations NULL #' @title #' **Get WNBA Stats API League Dashboard Player Shot Locations** #' @rdname wnba_leaguedashplayershotlocations #' @author Saiem Gilani #' @param college college #' @param conference conference #' @param country country #' @param date_from date_from #' @param date_to date_to #' @param distance_range distance_range #' @param division division #' @param draft_pick draft_pick #' @param draft_year draft_year #' @param dribble_range dribble_range #' @param game_scope game_scope #' @param game_segment game_segment #' @param height height #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param weight weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: ShotLocations #' #' **ShotLocations** #' #' #' |col_name |types | #' |:--------------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |AGE |character | #' |NICKNAME |character | #' |Restricted_Area_FGM |character | #' |Restricted_Area_FGA |character | #' |Restricted_Area_FG_PCT |character | #' |In_The_Paint_Non_RA_FGM |character | #' |In_The_Paint_Non_RA_FGA |character | #' |In_The_Paint_Non_RA_FG_PCT |character | #' |Mid_Range_FGM |character | #' |Mid_Range_FGA |character | #' |Mid_Range_FG_PCT |character | #' |Left_Corner_3_FGM |character | #' |Left_Corner_3_FGA |character | #' |Left_Corner_3_FG_PCT |character | #' |Right_Corner_3_FGM |character | #' |Right_Corner_3_FGA |character | #' |Right_Corner_3_FG_PCT |character | #' |Above_the_Break_3_FGM |character | #' |Above_the_Break_3_FGA |character | #' |Above_the_Break_3_FG_PCT |character | #' |Backcourt_FGM |character | #' |Backcourt_FGA |character | #' |Backcourt_FG_PCT |character | #' |Corner_3_FGM |character | #' |Corner_3_FGA |character | #' |Corner_3_FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @family WNBA Shooting Functions #' @details #' ```r #' wnba_leaguedashplayershotlocations(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashplayershotlocations <- function( college = '', conference = '', country = '', date_from = '', date_to = '', distance_range = 'By Zone', division = '', draft_pick = '', draft_year = '', dribble_range = '', game_scope = '', game_segment = '', height = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_experience = '', player_position = '', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', vs_conference = '', vs_division = '', weight = '', ...){ # distance_range <- gsub(' ', '+', distance_range) # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashplayershotlocations" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Conference = conference, Country = country, DateFrom = date_from, DateTo = date_to, Division = division, DistanceRange = distance_range, DraftPick = draft_pick, DraftYear = draft_year, DribbleRange = dribble_range, GameScope = game_scope, GameSegment = game_segment, Height = height, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet %>% data.frame(stringsAsFactors = F) %>% dplyr::as_tibble() columnsToSkip <- resp$resultSets$headers$columnsToSkip[[1]] columnSpan <- resp$resultSets$headers$columnSpan[[1]] json_names1 <- resp$resultSets$headers$columnNames[[1]] json_names_rep <- rep(json_names1, times = 1, each = columnSpan) json_names2 <- resp$resultSets$headers$columnNames[[2]] json_names <- c(json_names2[1:columnsToSkip], paste(json_names_rep, json_names2[(columnsToSkip + 1):30])) colnames(data) <- gsub('\\(|\\)|','', gsub(' |-','_',json_names)) return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard player shot locations data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard by Team Clutch Splits** #' @name wnba_leaguedashteamclutch NULL #' @title #' **Get WNBA Stats API League Dashboard by Team Clutch Splits** #' @rdname wnba_leaguedashteamclutch #' @author Saiem Gilani #' @param ahead_behind ahead_behind #' @param clutch_time clutch_time #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param game_scope game_scope #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param plus_minus plus_minus #' @param point_diff point_diff #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueDashTeamClutch #' #' **LeagueDashTeamClutch** #' #' #' |col_name |types | #' |:---------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Clutch Functions #' @details #' ```r #' wnba_leaguedashteamclutch(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashteamclutch <- function( ahead_behind = 'Ahead or Behind', clutch_time = 'Last 5 Minutes', conference = '', date_from = '', date_to = '', division = '', game_scope = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust='N', plus_minus = 'N', point_diff = 5, po_round = '', per_mode = 'Totals', period = 0, player_experience = '', player_position = '', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', vs_conference = '', vs_division = '', ...){ # ahead_behind <- gsub(' ', '+', ahead_behind) # clutch_time <- gsub(' ', '+', clutch_time) # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashteamclutch" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( AheadBehind = ahead_behind, ClutchTime = clutch_time, Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, GameScope = game_scope, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, PlusMinus = plus_minus, PointDiff = point_diff, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard team clutch data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard Team Stats** #' @name wnba_leaguedashteamstats NULL #' @title #' **Get WNBA Stats API League Dashboard Team Stats** #' @rdname wnba_leaguedashteamstats #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param game_scope game_scope #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param two_way two_way #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueDashTeamStats #' #' **LeagueDashTeamStats** #' #' #' |col_name |types | #' |:---------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Team Functions #' @details #' ```r #' wnba_leaguedashteamstats(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashteamstats <- function( conference = '', date_from = '', date_to = '', division = '', game_scope = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', two_way = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashteamstats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, GameScope = game_scope, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, TwoWay = two_way, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard team stats data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard Team Shot Locations** #' @name wnba_leaguedashteamshotlocations NULL #' @title #' **Get WNBA Stats API League Dashboard Team Shot Locations** #' @rdname wnba_leaguedashteamshotlocations #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param distance_range distance_range #' @param division division #' @param game_scope game_scope #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_experience player_experience #' @param player_position player_position #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: ShotLocations #' #' **ShotLocations** #' #' #' |col_name |types | #' |:--------------------------|:---------| #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |Restricted_Area_FGM |character | #' |Restricted_Area_FGA |character | #' |Restricted_Area_FG_PCT |character | #' |In_The_Paint_Non_RA_FGM |character | #' |In_The_Paint_Non_RA_FGA |character | #' |In_The_Paint_Non_RA_FG_PCT |character | #' |Mid_Range_FGM |character | #' |Mid_Range_FGA |character | #' |Mid_Range_FG_PCT |character | #' |Left_Corner_3_FGM |character | #' |Left_Corner_3_FGA |character | #' |Left_Corner_3_FG_PCT |character | #' |Right_Corner_3_FGM |character | #' |Right_Corner_3_FGA |character | #' |Right_Corner_3_FG_PCT |character | #' |Above_the_Break_3_FGM |character | #' |Above_the_Break_3_FGA |character | #' |Above_the_Break_3_FG_PCT |character | #' |Backcourt_FGM |character | #' |Backcourt_FGA |character | #' |Backcourt_FG_PCT |character | #' |Corner_3_FGM |character | #' |Corner_3_FGA |character | #' |Corner_3_FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Shooting Functions #' @details #' ```r #' wnba_leaguedashteamshotlocations(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashteamshotlocations <- function( conference = '', date_from = '', date_to = '', distance_range = 'By Zone', division = '', game_scope = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_experience = '', player_position = '', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', starter_bench = '', team_id = '', vs_conference = '', vs_division = '', ...){ # distance_range <- gsub(' ', '+', distance_range) # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashteamshotlocations" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, DistanceRange = distance_range, GameScope = game_scope, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerExperience = player_experience, PlayerPosition = player_position, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet %>% data.frame(stringsAsFactors = F) %>% dplyr::as_tibble() columnsToSkip <- resp$resultSets$headers$columnsToSkip[[1]] columnSpan <- resp$resultSets$headers$columnSpan[[1]] json_names1 <- resp$resultSets$headers$columnNames[[1]] json_names_rep <- rep(json_names1,times = 1, each = columnSpan) json_names2 <- resp$resultSets$headers$columnNames[[2]] json_names <- c(json_names2[1:columnsToSkip], paste(json_names_rep, json_names2[(columnsToSkip + 1):30])) colnames(data) <- gsub('\\(|\\)|','', gsub(' |-','_',json_names)) return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard team shot location data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_league_dash.R
#' **Get WNBA Stats API Fantasy Widget** #' @name wnba_fantasywidget NULL #' @title #' **Get WNBA Stats API Fantasy Widget** #' @rdname wnba_fantasywidget #' @author Saiem Gilani #' @param active_players active_players #' @param date_from date_from date_from #' @param date_to date_to date_to #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param po_round po_round #' @param player_id player_id #' @param position position #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param todays_opponent todays_opponent #' @param todays_players todays_players #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: FantasyWidgetResult #' #' **FantasyWidgetResult** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |PLAYER_POSITION |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |GP |character | #' |MIN |character | #' |FAN_DUEL_PTS |character | #' |NBA_FANTASY_PTS |character | #' |PTS |character | #' |REB |character | #' |AST |character | #' |BLK |character | #' |STL |character | #' |TOV |character | #' |FG3M |character | #' |FGA |character | #' |FG_PCT |character | #' |FTA |character | #' |FT_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Fantasy Functions #' @details #' ```r #' wnba_fantasywidget(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_fantasywidget <- function( active_players = 'N', date_from = '', date_to = '', last_n_games = 0, league_id = '10', location = '', month = '', opponent_team_id = '', po_round = '', player_id = '', position = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', todays_opponent = 0, todays_players = 'N', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "fantasywidget" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( ActivePlayers = active_players, DateFrom = date_from, DateTo = date_to, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, PORound = po_round, PlayerID = player_id, Position = position, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, TodaysOpponent = todays_opponent, TodaysPlayers = todays_players, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no fantasy widget data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Dashboard Lineups** #' @name wnba_leaguedashlineups NULL #' @title #' **Get WNBA Stats API League Dashboard Lineups** #' @rdname wnba_leaguedashlineups #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param game_segment game_segment #' @param group_quantity group_quantity #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: Lineups #' #' **Lineups** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_ID |character | #' |GROUP_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Lineup Functions #' @details #' ```r #' wnba_leaguedashlineups(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguedashlineups <- function( conference = '', date_from = '', date_to = '', division = '', game_segment = '', group_quantity = 5, last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguedashlineups" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, GameSegment = game_segment, GroupQuantity = group_quantity, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard lineups data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Lineup Visual Data** #' @name wnba_leaguelineupviz NULL #' @title #' **Get WNBA Stats API League Lineup Visual Data** #' @rdname wnba_leaguelineupviz #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param game_segment game_segment #' @param group_quantity group_quantity #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param minutes_min minutes_min #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: LeagueLineupViz #' #' **LeagueLineupViz** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_ID |character | #' |GROUP_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |MIN |character | #' |OFF_RATING |character | #' |DEF_RATING |character | #' |NET_RATING |character | #' |PACE |character | #' |TS_PCT |character | #' |FTA_RATE |character | #' |TM_AST_PCT |character | #' |PCT_FGA_2PT |character | #' |PCT_FGA_3PT |character | #' |PCT_PTS_2PT_MR |character | #' |PCT_PTS_FB |character | #' |PCT_PTS_FT |character | #' |PCT_PTS_PAINT |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |OPP_FG3_PCT |character | #' |OPP_EFG_PCT |character | #' |OPP_FTA_RATE |character | #' |OPP_TOV_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Lineup Functions #' @details #' ```r #' wnba_leaguelineupviz(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leaguelineupviz <- function( conference = '', date_from = '', date_to = '', division = '', game_segment = '', group_quantity = 5, last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', minutes_min = 10, month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leaguelineupviz" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, GameSegment = game_segment, GroupQuantity = group_quantity, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, MinutesMin = minutes_min, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league lineup viz data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Player On/Off Details** #' @name wnba_leagueplayerondetails NULL #' @title #' **Get WNBA Stats API League Player On/Off Details** #' @rdname wnba_leagueplayerondetails #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: PlayersOnCourtLeaguePlayerDetails #' #' **PlayersOnCourtLeaguePlayerDetails** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @details #' ```r #' wnba_leagueplayerondetails(team_id = '1611661313', season = most_recent_wnba_season() - 1) #' ``` wnba_leagueplayerondetails <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '1611661313', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leagueplayerondetails" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league player on/off details data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API League Season Matchups** #' @name wnba_leagueseasonmatchups NULL #' @title #' **Get WNBA Stats API League Season Matchups** #' @rdname wnba_leagueseasonmatchups #' @author Saiem Gilani #' @param def_player_id def_player_id #' @param def_team_id def_team_id #' @param league_id league_id #' @param off_player_id off_player_id #' @param off_team_id off_team_id #' @param per_mode per_mode #' @param season season #' @param season_type season_type #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: SeasonMatchups #' #' **SeasonMatchups** #' #' #' |col_name |types | #' |:----------------|:---------| #' |SEASON_ID |character | #' |OFF_PLAYER_ID |character | #' |OFF_PLAYER_NAME |character | #' |DEF_PLAYER_ID |character | #' |DEF_PLAYER_NAME |character | #' |GP |character | #' |MATCHUP_MIN |character | #' |PARTIAL_POSS |character | #' |PLAYER_PTS |character | #' |TEAM_PTS |character | #' |MATCHUP_AST |character | #' |MATCHUP_TOV |character | #' |MATCHUP_BLK |character | #' |MATCHUP_FGM |character | #' |MATCHUP_FGA |character | #' |MATCHUP_FG_PCT |character | #' |MATCHUP_FG3M |character | #' |MATCHUP_FG3A |character | #' |MATCHUP_FG3_PCT |character | #' |HELP_BLK |character | #' |HELP_FGM |character | #' |HELP_FGA |character | #' |HELP_FG_PERC |character | #' |MATCHUP_FTM |character | #' |MATCHUP_FTA |character | #' |SFL |character | #' |MATCHUP_TIME_SEC |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA League Functions #' @family WNBA Player Functions #' @details #' (No Matchups Data for WNBA yet, so defunct) #' ```r #' wnba_leagueseasonmatchups(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_leagueseasonmatchups <- function( def_player_id = '', def_team_id = '', league_id = '10', off_player_id = '', off_team_id = '', per_mode = 'Totals', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "leagueseasonmatchups" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DefPlayerID = def_player_id, DefTeamID = def_team_id, LeagueID = league_id, OffPlayerID = off_player_id, OffTeamID = off_team_id, PerMode = per_mode, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league season matchups data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_lineups.R
#' **Add players on court in WNBA Stats API play-by-play** #' @name .players_on_court NULL #' @title #' **Add players on court in WNBA Stats API play-by-play** #' @author Vladislav Shufinskiy #' @param pbp_data PlayByPlay data frame received `wnba_pbp` function #' @return Returns a data frame: PlayByPlay #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |event_num |character | #' |event_type |character | #' |event_action_type |character | #' |period |numeric | #' |minute_game |numeric | #' |time_remaining |numeric | #' |wc_time_string |character | #' |time_quarter |character | #' |minute_remaining_quarter |numeric | #' |seconds_remaining_quarter |numeric | #' |home_description |character | #' |neutral_description |character | #' |visitor_description |character | #' |score |character | #' |away_score |numeric | #' |home_score |numeric | #' |score_margin |character | #' |person1type |character | #' |player1_id |character | #' |player1_name |character | #' |player1_team_id |character | #' |player1_team_city |character | #' |player1_team_nickname |character | #' |player1_team_abbreviation |character | #' |person2type |character | #' |player2_id |character | #' |player2_name |character | #' |player2_team_id |character | #' |player2_team_city |character | #' |player2_team_nickname |character | #' |player2_team_abbreviation |character | #' |person3type |character | #' |player3_id |character | #' |player3_name |character | #' |player3_team_id |character | #' |player3_team_city |character | #' |player3_team_nickname |character | #' |player3_team_abbreviation |character | #' |video_available_flag |character | #' |team_leading |character | #' |away_player1 |numeric | #' |away_player2 |numeric | #' |away_player3 |numeric | #' |away_player4 |numeric | #' |away_player5 |numeric | #' |home_player1 |numeric | #' |home_player2 |numeric | #' |home_player3 |numeric | #' |home_player4 |numeric | #' |home_player5 |numeric | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @noRd #' @family WNBA PBP Functions .players_on_court <- function(pbp_data) { pbp_data <- dplyr::mutate(pbp_data, PCTIMESTRING = ifelse(.data$period < 5, abs((.data$minute_remaining_quarter * 60 + .data$seconds_remaining_quarter) - 720 * .data$period), abs((.data$minute_remaining_quarter * 60 + .data$seconds_remaining_quarter) - (2880 + 300 * (.data$period - 4))))) l <- lapply(sort(unique(pbp_data$period)), function(x){ pbp_data_period <- dplyr::filter(pbp_data, .data$period == x) all_id <- unique(c(pbp_data_period$player1_id[!pbp_data_period$event_type %in% c(9, 18) & !is.na(pbp_data_period$player1_name) & !pbp_data_period$person1type %in% c(6, 7)], pbp_data_period$player2_id[!pbp_data_period$event_type %in% c(9, 18) & !is.na(pbp_data_period$player2_name) & !pbp_data_period$person2type %in% c(6, 7)], pbp_data_period$player3_id[!pbp_data_period$event_type %in% c(9, 18) & !is.na(pbp_data_period$player3_name) & !pbp_data_period$person3type %in% c(6, 7)])) all_id <- as.numeric(all_id) all_id <- all_id[all_id != 0 & all_id < 1610612737] sub_off <- as.numeric(unique(pbp_data_period$player1_id[pbp_data_period$event_type == 8])) sub_on <- as.numeric(unique(pbp_data_period$player2_id[pbp_data_period$event_type == 8])) '%!in%' <- Negate(`%in%`) all_id <- all_id[all_id %!in% setdiff(sub_on, sub_off)] sub_on_off <- dplyr::intersect(sub_on, sub_off) for (i in sub_on_off){ on <- min(pbp_data_period$PCTIMESTRING[pbp_data_period$event_type == 8 & pbp_data_period$player2_id == i]) off <- min(pbp_data_period$PCTIMESTRING[pbp_data_period$event_type == 8 & pbp_data_period$player1_id == i]) if (off > on){ all_id <- all_id[all_id != i] } else if (off == on){ on_event <- min(pbp_data_period$event_num[pbp_data_period$event_type == 8 & pbp_data_period$player2_id == i]) off_event <- min(pbp_data_period$event_num[pbp_data_period$event_type == 8 & pbp_data_period$player1_id == i]) if(off_event > on_event){ all_id <- all_id[all_id != i] } } } if((length(all_id) == 10)){ ord_all_id <- pbp_data_period %>% dplyr::select("player1_id", "person1type") %>% dplyr::filter(.data$player1_id != 0 & .data$person1type %in% c(4, 5)) %>% dplyr::rename("player_id" = "player1_id", "persontype" = "person1type") %>% dplyr::bind_rows(pbp_data_period %>% dplyr::select("player2_id", "person2type") %>% dplyr::filter(.data$player2_id != 0 & .data$person2type %in% c(4, 5)) %>% dplyr::rename("player_id" = "player2_id", "persontype" = "person2type")) %>% dplyr::bind_rows(pbp_data_period %>% dplyr::select("player3_id", "person3type") %>% dplyr::filter(.data$player3_id != 0 & .data$person3type %in% c(4, 5)) %>% dplyr::rename("player_id" = "player3_id", "persontype" = "person3type")) %>% dplyr::distinct() %>% dplyr::arrange(dplyr::desc(.data$persontype)) %>% dplyr::select("player_id") %>% dplyr::mutate(player_id = as.numeric(.data$player_id)) %>% dplyr::pull() all_id <- ord_all_id[ord_all_id %in% all_id] } if(length(all_id) != 10){ if(inherits(pbp_data$game_id[1], "integer")){ tmp_gameid <- paste0("00", as.character(pbp_data$game_id[1])) } else{ tmp_gameid <- pbp_data$game_id[1] } tmp_data <- wnba_boxscoretraditionalv2(game_id = tmp_gameid, start_period = x, end_period = x, range_type = 1)$PlayerStats all_id <- as.integer(tmp_data$PLAYER_ID) sub_off <- unique(pbp_data_period$player1_id[pbp_data_period$event_type == 8]) sub_on <- unique(pbp_data_period$player2_id[pbp_data_period$event_type == 8]) '%!in%' <- Negate(`%in%`) all_id <- all_id[all_id %!in% setdiff(sub_on, sub_off)] sub_on_off <- dplyr::intersect(sub_on, sub_off) for (i in sub_on_off){ on <- min(pbp_data_period$PCTIMESTRING[pbp_data_period$event_type == 8 & pbp_data_period$player2_id == i]) off <- min(pbp_data_period$PCTIMESTRING[pbp_data_period$event_type == 8 & pbp_data_period$player1_id == i]) if (off > on){ all_id <- all_id[all_id != i] } else if (off == on){ on_event <- min(pbp_data_period$even_num[pbp_data_period$event_type == 8 & pbp_data_period$player2_id == i]) off_event <- min(pbp_data_period$even_num[pbp_data_period$event_type == 8 & pbp_data_period$player1_id == i]) if(off_event > on_event){ all_id <- all_id[all_id != i] } } } } columns <- paste0("player", seq(1, 10)) pbp_data_period[columns] <- NA for(i in seq(1:10)){ pbp_data_period[columns][i] <- all_id[i] } for(column in paste0("player", seq(1, 10))){ i <- 1 repeat{ n <- nrow(pbp_data_period) if(length(which(pbp_data_period$event_type == 8 & as.numeric(pbp_data_period$player1_id) == pbp_data_period[, column])) == 0){ break } i <- min(which(pbp_data_period$event_type == 8 & pbp_data_period[, column] == as.numeric(pbp_data_period$player1_id))) player_on <- as.numeric(pbp_data_period$player2_id[i]) pbp_data_period[i:n, column] <- player_on } } return(dplyr::select(pbp_data_period, -"PCTIMESTRING")) }) return(dplyr::bind_rows(l) %>% dplyr::rename( "away_player1" = 'player1', "away_player2" = 'player2', "away_player3" = 'player3', "away_player4" = 'player4', "away_player5" = 'player5', "home_player1" = 'player6', "home_player2" = 'player7', "home_player3" = 'player8', "home_player4" = 'player9', "home_player5" = 'player10' )) } #' **Get WNBA Stats API play-by-play** #' @name wnba_pbp NULL #' @title #' **Get WNBA Stats API play-by-play** #' @rdname wnba_pbp #' @param game_id Game ID #' @param on_court IF TRUE will be added ID of players on court #' @param version Play-by-play version ("v2" available from 2016-17 onwards) #' @param p Progress bar #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a data frame: PlayByPlay #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |event_num |character | #' |event_type |character | #' |event_action_type |character | #' |period |numeric | #' |minute_game |numeric | #' |time_remaining |numeric | #' |wc_time_string |character | #' |time_quarter |character | #' |minute_remaining_quarter |numeric | #' |seconds_remaining_quarter |numeric | #' |home_description |character | #' |neutral_description |character | #' |visitor_description |character | #' |score |character | #' |away_score |numeric | #' |home_score |numeric | #' |score_margin |character | #' |person1type |character | #' |player1_id |character | #' |player1_name |character | #' |player1_team_id |character | #' |player1_team_city |character | #' |player1_team_nickname |character | #' |player1_team_abbreviation |character | #' |person2type |character | #' |player2_id |character | #' |player2_name |character | #' |player2_team_id |character | #' |player2_team_city |character | #' |player2_team_nickname |character | #' |player2_team_abbreviation |character | #' |person3type |character | #' |player3_id |character | #' |player3_name |character | #' |player3_team_id |character | #' |player3_team_city |character | #' |player3_team_nickname |character | #' |player3_team_abbreviation |character | #' |video_available_flag |character | #' |team_leading |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA PBP Functions #' @details #' ```r #' wnba_pbp(game_id = "1022200034", on_court = TRUE) #' ``` wnba_pbp <- function(game_id, on_court = TRUE, version = "v2", p, ...){ if (version == "v2") { endpoint <- wnba_endpoint('playbyplayv2') } else { endpoint <- wnba_endpoint('playbyplay') } full_url <- endpoint params <- list( EndPeriod = 0, GameID = pad_id(game_id), StartPeriod = 0 ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) # if (return_message) { # glue::glue("Getting play by play for game {game_id}") %>% cat(fill = T) # } data <- resp$resultSets$rowSet[[1]] %>% data.frame() %>% dplyr::as_tibble() json_names <- resp$resultSets$headers[[1]] colnames(data) <- json_names # Fix version 2 Dataset if (version == "v2") { data <- data %>% # fix column names janitor::clean_names() %>% dplyr::rename(dplyr::any_of(c( "wc_time_string" = "wctimestring", "time_quarter" = "pctimestring", "score_margin" = "scoremargin", "event_num" = "eventnum", "event_type" = "eventmsgtype", "event_action_type" = "eventmsgactiontype", "home_description" = "homedescription", "neutral_description" = "neutraldescription", "visitor_description" = "visitordescription" ))) %>% ## Get Team Scores tidyr::separate( "score", into = c("away_score", "home_score"), sep = "\\ - ", remove = FALSE ) %>% dplyr::mutate( home_score = as.numeric(.data$home_score), away_score = as.numeric(.data$away_score), team_leading = dplyr::case_when( .data$score_margin == 0 ~ "Tie", .data$score_margin < 0 ~ "Away", is.na(.data$score_margin) ~ NA_character_, TRUE ~ "Home" ) ) %>% ## Time Remaining tidyr::separate( "time_quarter", into = c("minute_remaining_quarter", "seconds_remaining_quarter"), sep = "\\:", remove = F ) %>% dplyr::mutate( minute_remaining_quarter = as.numeric(.data$minute_remaining_quarter), seconds_remaining_quarter = as.numeric(.data$seconds_remaining_quarter), period = as.numeric(.data$period) ) %>% dplyr::mutate( minute_game = round(((.data$period - 1) * 12) + (12 - .data$minute_remaining_quarter) + ((( 60 - .data$seconds_remaining_quarter ) / 60) - 1), 2), time_remaining = 40 - round(((.data$period - 1) * 12) - (12 - .data$minute_remaining_quarter) - ((60 - .data$seconds_remaining_quarter) / 60 - 1), 2) ) %>% dplyr::select( "game_id":"period", "minute_game", "time_remaining", dplyr::everything() ) %>% make_wehoop_data("WNBA Game Play-by-Play Information from WNBA.com", Sys.time()) if(on_court){ data <- .players_on_court(data) } } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no play-by-play data for {pad_id(game_id)} available!")) }, warning = function(w) { }, finally = { } ) return(data) } #' **Get WNBA Stats API play-by-play (Multiple Games)** #' @name wnba_pbps NULL #' @title #' **Get WNBA Stats API play-by-play (Multiple Games)** #' @rdname wnba_pbps #' @author Jason Lee #' @param game_ids Game IDs #' @param on_court IF TRUE will be added ID of players on court #' @param version Play-by-play version ("v2" available from 2016-17 onwards) #' @param nest_data If TRUE returns nested data by game #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a data frame: PlayByPlay #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |event_num |character | #' |event_type |character | #' |event_action_type |character | #' |period |numeric | #' |minute_game |numeric | #' |time_remaining |numeric | #' |wc_time_string |character | #' |time_quarter |character | #' |minute_remaining_quarter |numeric | #' |seconds_remaining_quarter |numeric | #' |home_description |character | #' |neutral_description |character | #' |visitor_description |character | #' |score |character | #' |away_score |numeric | #' |home_score |numeric | #' |score_margin |character | #' |person1type |character | #' |player1_id |character | #' |player1_name |character | #' |player1_team_id |character | #' |player1_team_city |character | #' |player1_team_nickname |character | #' |player1_team_abbreviation |character | #' |person2type |character | #' |player2_id |character | #' |player2_name |character | #' |player2_team_id |character | #' |player2_team_city |character | #' |player2_team_nickname |character | #' |player2_team_abbreviation |character | #' |person3type |character | #' |player3_id |character | #' |player3_name |character | #' |player3_team_id |character | #' |player3_team_city |character | #' |player3_team_nickname |character | #' |player3_team_abbreviation |character | #' |video_available_flag |character | #' |team_leading |character | #' |away_player1 |numeric | #' |away_player2 |numeric | #' |away_player3 |numeric | #' |away_player4 |numeric | #' |away_player5 |numeric | #' |home_player1 |numeric | #' |home_player2 |numeric | #' |home_player3 |numeric | #' |home_player4 |numeric | #' |home_player5 |numeric | #' #' @export #' @family WNBA PBP Functions #' @details #' ```r #' y <- c("1022200034", "1022200035" ) #' #' wnba_pbps(game_ids = y, version = "v2") #' ``` wnba_pbps <- function( game_ids = NULL, on_court = TRUE, version = "v2", nest_data = FALSE, ...) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) if (game_ids %>% purrr::is_null()) { stop("Please enter game ids") } p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = game_ids) get_pbp_safe <- progressively(wnba_pbp, p) all_data <- game_ids %>% purrr::map_dfr(function(game_id) { get_pbp_safe(game_id = game_id, on_court = on_court, ..., p = p) }) if (nest_data) { all_data <- all_data %>% dplyr::group_by(.data$game_id) %>% tidyr::nest() } return(all_data) } #' **Get WNBA Stats API Live play-by-play** #' @name wnba_live_pbp NULL #' @title #' **Get WNBA Stats API Live play-by-play** #' @rdname wnba_live_pbp #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a data frame: PlayByPlay #' #' |col_name |types | #' |:----------------------------|:---------| #' |event_num |integer | #' |clock |character | #' |time_actual |character | #' |period |integer | #' |period_type |character | #' |action_type |character | #' |sub_type |character | #' |qualifiers |list | #' |player1_id |integer | #' |x |numeric | #' |y |numeric | #' |offense_team_id |integer | #' |home_score |character | #' |away_score |character | #' |edited |character | #' |order |integer | #' |x_legacy |integer | #' |y_legacy |integer | #' |is_field_goal |integer | #' |side |character | #' |description |character | #' |person_ids_filter |list | #' |team_id |integer | #' |team_tricode |character | #' |descriptor |character | #' |jump_ball_recovered_name |character | #' |jump_ball_recoverd_person_id |integer | #' |player_name |character | #' |player_name_i |character | #' |jump_ball_won_player_name |character | #' |jump_ball_won_person_id |integer | #' |jump_ball_lost_player_name |character | #' |jump_ball_lost_person_id |integer | #' |shot_distance |numeric | #' |shot_result |character | #' |shot_action_number |integer | #' |rebound_total |integer | #' |rebound_defensive_total |integer | #' |rebound_offensive_total |integer | #' |turnover_total |integer | #' |steal_player_name |character | #' |steal_person_id |integer | #' |points_total |integer | #' |assist_player_name_initial |character | #' |assist_person_id |integer | #' |assist_total |integer | #' |official_id |integer | #' |foul_personal_total |integer | #' |foul_technical_total |integer | #' |foul_drawn_player_name |character | #' |foul_drawn_person_id |integer | #' |block_player_name |character | #' |block_person_id |integer | #' |value |character | #' |player2_id |integer | #' |player3_id |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA PBP Functions #' @family WNBA Live Functions #' @details #' ```r #' wnba_live_pbp(game_id = "1022200034") #' ``` wnba_live_pbp <- function( game_id, ...){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) endpoint <- wnba_live_endpoint('playbyplay') full_url <- paste0(endpoint, "/playbyplay_", pad_id(game_id), ".json") tryCatch( expr = { res <- rvest::session(url = full_url, ..., httr::timeout(60)) resp <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() data <- resp %>% purrr::pluck("game") %>% purrr::pluck("actions") %>% janitor::clean_names() data <- data %>% dplyr::rename(dplyr::any_of(c( "period" = "period", "event_num" = "action_number", "clock" = "clock", "description" = "description", "locX" = "xLegacy", "locY" = "yLegacy", "action_type" = "action_type", "sub_type" = "sub_type", "descriptor" = "descriptor", "shot_result" = "shot_result", "shot_action_number" = "shot_action_number", "qualifiers" = "qualifiers", "team_id" = "team_id", "player1_id" = "person_id", "home_score" = "score_home", "away_score" = "score_away", "offense_team_id" = "possession", "order" = "order_number"))) %>% dplyr::mutate( player2_id = dplyr::case_when( !is.na(.data$assist_person_id) ~ .data$assist_person_id, TRUE ~ NA_integer_), player3_id = dplyr::case_when( !is.na(.data$block_person_id) ~ .data$block_person_id, !is.na(.data$steal_person_id) ~ .data$steal_person_id, !is.na(.data$foul_drawn_person_id) ~ .data$foul_drawn_person_id, TRUE ~ NA_integer_ )) %>% make_wehoop_data("WNBA Game Play-by-Play Information from WNBA.com", Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no play-by-play data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(data) } #' **Get WNBA Stats API Live Boxscore** #' @name wnba_live_boxscore NULL #' @title #' **Get WNBA Stats API Live Boxscore** #' @rdname wnba_live_boxscore #' @author Saiem Gilani #' @param game_id Game ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a named list of data frames: game_details, arena, officials, home_team_boxscore, #' away_team_boxscore, home_team_player_boxscore, away_team_player_boxscore, home_team_linescores, #' away_team_linescores #' #' **game_details** #' #' #' |col_name |types | #' |:----------------------------|:---------| #' |game_id |character | #' |game_time_local |character | #' |game_time_utc |character | #' |game_time_home |character | #' |game_time_away |character | #' |game_et |character | #' |duration |integer | #' |game_code |character | #' |game_status_text |character | #' |game_status |integer | #' |regulation_periods |integer | #' |period |integer | #' |game_clock |character | #' |attendance |integer | #' |sellout |character | #' |home_team_id |integer | #' |home_team_name |character | #' |home_team_city |character | #' |home_team_tricode |character | #' |home_team_score |integer | #' |home_team_in_bonus |character | #' |home_team_timeouts_remaining |integer | #' |away_team_id |integer | #' |away_team_name |character | #' |away_team_city |character | #' |away_team_tricode |character | #' |away_team_score |integer | #' |away_team_in_bonus |character | #' |away_team_timeouts_remaining |integer | #' #' **arena** #' #' #' |col_name |types | #' |:--------------|:---------| #' |arena_id |integer | #' |arena_name |character | #' |arena_city |character | #' |arena_state |character | #' |arena_country |character | #' |arena_timezone |character | #' #' **officials** #' #' #' |col_name |types | #' |:-----------|:---------| #' |person_id |integer | #' |name |character | #' |name_i |character | #' |first_name |character | #' |family_name |character | #' |jersey_num |character | #' |assignment |character | #' #' **home_team_boxscore** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_score |integer | #' |team_in_bonus |character | #' |team_timeouts_remaining |integer | #' |assists |integer | #' |assists_turnover_ratio |numeric | #' |bench_points |integer | #' |biggest_lead |integer | #' |biggest_lead_score |character | #' |biggest_scoring_run |integer | #' |biggest_scoring_run_score |character | #' |blocks |integer | #' |blocks_received |integer | #' |fast_break_points_attempted |integer | #' |fast_break_points_made |integer | #' |fast_break_points_percentage |numeric | #' |field_goals_attempted |integer | #' |field_goals_effective_adjusted |numeric | #' |field_goals_made |integer | #' |field_goals_percentage |numeric | #' |fouls_offensive |integer | #' |fouls_drawn |integer | #' |fouls_personal |integer | #' |fouls_team |integer | #' |fouls_technical |integer | #' |fouls_team_technical |integer | #' |free_throws_attempted |integer | #' |free_throws_made |integer | #' |free_throws_percentage |numeric | #' |lead_changes |integer | #' |minutes |character | #' |minutes_calculated |character | #' |points |integer | #' |points_against |integer | #' |points_fast_break |integer | #' |points_from_turnovers |integer | #' |points_in_the_paint |integer | #' |points_in_the_paint_attempted |integer | #' |points_in_the_paint_made |integer | #' |points_in_the_paint_percentage |numeric | #' |points_second_chance |integer | #' |rebounds_defensive |integer | #' |rebounds_offensive |integer | #' |rebounds_personal |integer | #' |rebounds_team |integer | #' |rebounds_team_defensive |integer | #' |rebounds_team_offensive |integer | #' |rebounds_total |integer | #' |second_chance_points_attempted |integer | #' |second_chance_points_made |integer | #' |second_chance_points_percentage |numeric | #' |steals |integer | #' |three_pointers_attempted |integer | #' |three_pointers_made |integer | #' |three_pointers_percentage |numeric | #' |time_leading |character | #' |times_tied |integer | #' |true_shooting_attempts |numeric | #' |true_shooting_percentage |numeric | #' |turnovers |integer | #' |turnovers_team |integer | #' |turnovers_total |integer | #' |two_pointers_attempted |integer | #' |two_pointers_made |integer | #' |two_pointers_percentage |numeric | #' #' **away_team_boxscore** #' #' #' |col_name |types | #' |:-------------------------------|:---------| #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_score |integer | #' |team_in_bonus |character | #' |team_timeouts_remaining |integer | #' |assists |integer | #' |assists_turnover_ratio |numeric | #' |bench_points |integer | #' |biggest_lead |integer | #' |biggest_lead_score |character | #' |biggest_scoring_run |integer | #' |biggest_scoring_run_score |character | #' |blocks |integer | #' |blocks_received |integer | #' |fast_break_points_attempted |integer | #' |fast_break_points_made |integer | #' |fast_break_points_percentage |numeric | #' |field_goals_attempted |integer | #' |field_goals_effective_adjusted |numeric | #' |field_goals_made |integer | #' |field_goals_percentage |numeric | #' |fouls_offensive |integer | #' |fouls_drawn |integer | #' |fouls_personal |integer | #' |fouls_team |integer | #' |fouls_technical |integer | #' |fouls_team_technical |integer | #' |free_throws_attempted |integer | #' |free_throws_made |integer | #' |free_throws_percentage |numeric | #' |lead_changes |integer | #' |minutes |character | #' |minutes_calculated |character | #' |points |integer | #' |points_against |integer | #' |points_fast_break |integer | #' |points_from_turnovers |integer | #' |points_in_the_paint |integer | #' |points_in_the_paint_attempted |integer | #' |points_in_the_paint_made |integer | #' |points_in_the_paint_percentage |numeric | #' |points_second_chance |integer | #' |rebounds_defensive |integer | #' |rebounds_offensive |integer | #' |rebounds_personal |integer | #' |rebounds_team |integer | #' |rebounds_team_defensive |integer | #' |rebounds_team_offensive |integer | #' |rebounds_total |integer | #' |second_chance_points_attempted |integer | #' |second_chance_points_made |integer | #' |second_chance_points_percentage |numeric | #' |steals |integer | #' |three_pointers_attempted |integer | #' |three_pointers_made |integer | #' |three_pointers_percentage |numeric | #' |time_leading |character | #' |times_tied |integer | #' |true_shooting_attempts |numeric | #' |true_shooting_percentage |numeric | #' |turnovers |integer | #' |turnovers_team |integer | #' |turnovers_total |integer | #' |two_pointers_attempted |integer | #' |two_pointers_made |integer | #' |two_pointers_percentage |numeric | #' #' **home_team_player_boxscore** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_score |integer | #' |team_in_bonus |character | #' |team_timeouts_remaining |integer | #' |status |character | #' |order |integer | #' |person_id |integer | #' |jersey_num |character | #' |position |character | #' |starter |character | #' |oncourt |character | #' |played |character | #' |assists |integer | #' |blocks |integer | #' |blocks_received |integer | #' |field_goals_attempted |integer | #' |field_goals_made |integer | #' |field_goals_percentage |numeric | #' |fouls_offensive |integer | #' |fouls_drawn |integer | #' |fouls_personal |integer | #' |fouls_technical |integer | #' |free_throws_attempted |integer | #' |free_throws_made |integer | #' |free_throws_percentage |numeric | #' |minus |numeric | #' |minutes |character | #' |minutes_calculated |character | #' |plus |numeric | #' |plus_minus_points |numeric | #' |points |integer | #' |points_fast_break |integer | #' |points_in_the_paint |integer | #' |points_second_chance |integer | #' |rebounds_defensive |integer | #' |rebounds_offensive |integer | #' |rebounds_total |integer | #' |steals |integer | #' |three_pointers_attempted |integer | #' |three_pointers_made |integer | #' |three_pointers_percentage |numeric | #' |turnovers |integer | #' |two_pointers_attempted |integer | #' |two_pointers_made |integer | #' |two_pointers_percentage |numeric | #' |name |character | #' |name_i |character | #' |first_name |character | #' |family_name |character | #' |not_playing_reason |character | #' |not_playing_description |character | #' #' **away_team_player_boxscore** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |team_id |integer | #' |team_name |character | #' |team_city |character | #' |team_tricode |character | #' |team_score |integer | #' |team_in_bonus |character | #' |team_timeouts_remaining |integer | #' |status |character | #' |order |integer | #' |person_id |integer | #' |jersey_num |character | #' |position |character | #' |starter |character | #' |oncourt |character | #' |played |character | #' |assists |integer | #' |blocks |integer | #' |blocks_received |integer | #' |field_goals_attempted |integer | #' |field_goals_made |integer | #' |field_goals_percentage |numeric | #' |fouls_offensive |integer | #' |fouls_drawn |integer | #' |fouls_personal |integer | #' |fouls_technical |integer | #' |free_throws_attempted |integer | #' |free_throws_made |integer | #' |free_throws_percentage |numeric | #' |minus |numeric | #' |minutes |character | #' |minutes_calculated |character | #' |plus |numeric | #' |plus_minus_points |numeric | #' |points |integer | #' |points_fast_break |integer | #' |points_in_the_paint |integer | #' |points_second_chance |integer | #' |rebounds_defensive |integer | #' |rebounds_offensive |integer | #' |rebounds_total |integer | #' |steals |integer | #' |three_pointers_attempted |integer | #' |three_pointers_made |integer | #' |three_pointers_percentage |numeric | #' |turnovers |integer | #' |two_pointers_attempted |integer | #' |two_pointers_made |integer | #' |two_pointers_percentage |numeric | #' |name |character | #' |name_i |character | #' |first_name |character | #' |family_name |character | #' |not_playing_reason |character | #' |not_playing_description |character | #' #' **home_team_linescores** #' #' #' |col_name |types | #' |:-----------|:---------| #' |period |integer | #' |period_type |character | #' |score |integer | #' #' **away_team_linescores** #' #' #' |col_name |types | #' |:-----------|:---------| #' |period |integer | #' |period_type |character | #' |score |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family NBA Boxscore Functions #' @family NBA Live Functions #' @details #' ```r #' wnba_live_boxscore(game_id = "1022200034") #' ``` wnba_live_boxscore <- function( game_id, ...){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) endpoint <- wnba_live_endpoint('boxscore') full_url <- paste0(endpoint, "/boxscore_", pad_id(game_id), ".json") tryCatch( expr = { res <- rvest::session(url = full_url, ..., httr::timeout(60)) resp <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() data <- resp %>% purrr::pluck("game") game_details <- data.frame( game_id = data %>% purrr::pluck("gameId"), game_time_local = data %>% purrr::pluck("gameTimeLocal"), game_time_utc = data %>% purrr::pluck("gameTimeUTC"), game_time_home = data %>% purrr::pluck("gameTimeHome"), game_time_away = data %>% purrr::pluck("gameTimeAway"), game_et = data %>% purrr::pluck("gameEt"), duration = data %>% purrr::pluck("duration"), game_code = data %>% purrr::pluck("gameCode"), game_status_text = data %>% purrr::pluck("gameStatusText"), game_status = data %>% purrr::pluck("gameStatus"), regulation_periods = data %>% purrr::pluck("regulationPeriods"), period = data %>% purrr::pluck("period"), game_clock = data %>% purrr::pluck("gameClock"), attendance = data %>% purrr::pluck("attendance"), sellout = data %>% purrr::pluck("sellout") ) arena <- data %>% purrr::pluck("arena") %>% data.frame() %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Arena Information from WNBA.com", Sys.time()) officials <- data %>% purrr::pluck("officials") %>% data.frame() %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Officials Information from WNBA.com", Sys.time()) if ("homeTeam" %in% names(data)) { home_team <- data %>% purrr::pluck("homeTeam") home_team_info <- data.frame( team_id = home_team %>% purrr::pluck("teamId"), team_name = home_team %>% purrr::pluck("teamName"), team_city = home_team %>% purrr::pluck("teamCity"), team_tricode = home_team %>% purrr::pluck("teamTricode"), team_score = home_team %>% purrr::pluck("score"), team_in_bonus = home_team %>% purrr::pluck("inBonus"), team_timeouts_remaining = home_team %>% purrr::pluck("timeoutsRemaining") ) home_team_box <- home_team %>% purrr::pluck("statistics") %>% data.frame() home_team_linescores <- home_team$periods %>% janitor::clean_names() home_team_players <- home_team %>% purrr::pluck("players") %>% tidyr::unnest("statistics") home_team_player_boxscore <- home_team_info %>% dplyr::bind_cols(home_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Player Boxscore Information from WNBA.com", Sys.time()) home_team_boxscore <- home_team_info %>% dplyr::bind_cols(home_team_box) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Team Boxscore Information from WNBA.com", Sys.time()) } if ("awayTeam" %in% names(data)) { away_team <- data %>% purrr::pluck("awayTeam") away_team_info <- data.frame( team_id = away_team %>% purrr::pluck("teamId"), team_name = away_team %>% purrr::pluck("teamName"), team_city = away_team %>% purrr::pluck("teamCity"), team_tricode = away_team %>% purrr::pluck("teamTricode"), team_score = away_team %>% purrr::pluck("score"), team_in_bonus = away_team %>% purrr::pluck("inBonus"), team_timeouts_remaining = away_team %>% purrr::pluck("timeoutsRemaining") ) away_team_box <- away_team %>% purrr::pluck("statistics") %>% data.frame() away_team_linescores <- away_team$periods %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Linescore Information from WNBA.com", Sys.time()) away_team_players <- away_team %>% purrr::pluck("players") %>% tidyr::unnest("statistics") away_team_player_boxscore <- away_team_info %>% dplyr::bind_cols(away_team_players) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Player Boxscore Information from WNBA.com", Sys.time()) away_team_boxscore <- away_team_info %>% dplyr::bind_cols(away_team_box) %>% janitor::clean_names() %>% make_wehoop_data("WNBA Game Team Boxscore Information from WNBA.com", Sys.time()) } colnames(home_team_info) <- paste0("home_", colnames(home_team_info)) colnames(away_team_info) <- paste0("away_", colnames(away_team_info)) game_details <- game_details %>% dplyr::bind_cols(home_team_info) %>% dplyr::bind_cols(away_team_info) %>% make_wehoop_data("WNBA Game Linescore Information from WNBA.com", Sys.time()) df_list <- c( list(game_details), list(arena), list(officials), list(home_team_boxscore), list(away_team_boxscore), list(home_team_player_boxscore), list(away_team_player_boxscore), list(home_team_linescores), list(away_team_linescores) ) names(df_list) = c( "game_details", "arena", "officials", "home_team_boxscore", "away_team_boxscore", "home_team_player_boxscore", "away_team_player_boxscore", "home_team_linescores", "away_team_linescores" ) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no boxscore data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_pbp.R
#' **Get WNBA Stats API Player Index** #' @name wnba_playerindex NULL #' @title #' **Get WNBA Stats API Player Index** #' @rdname wnba_playerindex #' @author Saiem Gilani #' @param college Player College #' @param country Player Country #' @param draft_pick Draft Pick #' @param draft_round Draft Round #' @param draft_year Draft Year #' @param height Player Height #' @param historical Whether to include only current players (0) or all historical (1). #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param team_id Team ID. Default: 0 (all teams). #' @param weight Player weight #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerIndex #' #' **PlayerIndex** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PERSON_ID |character | #' |PLAYER_LAST_NAME |character | #' |PLAYER_FIRST_NAME |character | #' |PLAYER_SLUG |character | #' |TEAM_ID |character | #' |TEAM_SLUG |character | #' |IS_DEFUNCT |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |JERSEY_NUMBER |character | #' |POSITION |character | #' |HEIGHT |character | #' |WEIGHT |character | #' |COLLEGE |character | #' |COUNTRY |character | #' |DRAFT_YEAR |character | #' |DRAFT_ROUND |character | #' |DRAFT_NUMBER |character | #' |ROSTER_STATUS |character | #' |PTS |character | #' |REB |character | #' |AST |character | #' |STATS_TIMEFRAME |character | #' |FROM_YEAR |character | #' |TO_YEAR |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerindex() #' ``` wnba_playerindex <- function( college = '', country = '', draft_pick = '', draft_round = '', draft_year = '', height = '', historical = 1, league_id = '10', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', team_id = '0', weight = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerindex" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, Country = country, DraftPick = draft_pick, DraftRound = draft_round, DraftYear = draft_year, Height = height, Historical = historical, LeagueID = league_id, Season = season, SeasonType = season_type, TeamID = team_id, Weight = weight ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player index data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Head-shot** #' @name wnba_playerheadshot NULL #' @title #' **Get WNBA Stats API Player Head-shot** #' @rdname wnba_playerheadshot #' @author Saiem Gilani #' @param player_id Player ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Returns a url of the png for the player_id selected #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerheadshot(player_id = '1628932') #' ``` wnba_playerheadshot <- function( player_id = '1628932', ...){ endpoint <- "https://cdn.wnba.com/headshots/wnba/latest/260x190/" full_url <- paste0(endpoint, player_id,".png") tryCatch( expr = { resp <- full_url }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player headshot for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(resp) } #' **Get WNBA Stats API Player Awards** #' @name wnba_playerawards NULL #' @title #' **Get WNBA Stats API Player Awards** #' @rdname wnba_playerawards #' @author Saiem Gilani #' @param player_id Player ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerAwards #' #' **PlayerAwards** #' #' #' |col_name |types | #' |:-------------------|:---------| #' |PERSON_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |TEAM |character | #' |DESCRIPTION |character | #' |ALL_WNBA_TEAM_NUMBER |character | #' |SEASON |character | #' |MONTH |character | #' |WEEK |character | #' |CONFERENCE |character | #' |TYPE |character | #' |SUBTYPE1 |character | #' |SUBTYPE2 |character | #' |SUBTYPE3 |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' [Player Awards](https://stats.wnba.com/player/1628932/career/) #' ```r #' wnba_playerawards(player_id = '1628932') #' ``` wnba_playerawards <- function( player_id, ...){ version <- "playerawards" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( PlayerID = player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player awards data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Career By College** #' @name wnba_playercareerbycollege NULL #' @title #' **Get WNBA Stats API Player Career By College** #' @rdname wnba_playercareerbycollege #' @author Saiem Gilani #' @param college College Name #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param per_mode Per Mode - PerGame, Totals #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerCareerByCollege #' #' **PlayerCareerByCollege** #' #' #' |col_name |types | #' |:-----------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |COLLEGE |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |PF |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playercareerbycollege(college = 'Florida State', per_mode = 'PerGame') #' ``` wnba_playercareerbycollege <- function( college = 'Florida State', league_id = '10', per_mode = 'Totals', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # college <- gsub(' ', '+', college) # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playercareerbycollege" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( College = college, LeagueID = league_id, PerMode = per_mode, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player careers by college data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Career By College Rollup** #' @name wnba_playercareerbycollegerollup NULL #' @title #' **Get WNBA Stats API Player Career By College Rollup** #' @rdname wnba_playercareerbycollegerollup #' @author Saiem Gilani #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param per_mode Per Mode - PerGame, Totals #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: East, Midwest, South, West #' #' **East** #' #' #' |col_name |types | #' |:--------|:---------| #' |REGION |character | #' |SEED |character | #' |COLLEGE |character | #' |PLAYERS |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **South** #' #' #' |col_name |types | #' |:--------|:---------| #' |REGION |character | #' |SEED |character | #' |COLLEGE |character | #' |PLAYERS |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **Midwest** #' #' #' |col_name |types | #' |:--------|:---------| #' |REGION |character | #' |SEED |character | #' |COLLEGE |character | #' |PLAYERS |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **West** #' #' #' |col_name |types | #' |:--------|:---------| #' |REGION |character | #' |SEED |character | #' |COLLEGE |character | #' |PLAYERS |character | #' |GP |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playercareerbycollegerollup(per_mode = 'Totals') #' ``` wnba_playercareerbycollegerollup <- function( league_id = '10', per_mode = 'Totals', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playercareerbycollegerollup" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player careers by college rollup data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Career Stats** #' @name wnba_playercareerstats NULL #' @title #' **Get WNBA Stats API Player Career Stats** #' @rdname wnba_playercareerstats #' @author Saiem Gilani #' @param player_id Player ID #' @param per_mode Per Mode - PerGame, Totals #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: CareerTotalsAllStarSeason, #' CareerTotalsCollegeSeason, CareerTotalsPostSeason, #' CareerTotalsRegularSeason, SeasonRankingsPostSeason, #' SeasonRankingsRegularSeason, SeasonTotalsAllStarSeason, SeasonTotalsCollegeSeason, #' SeasonTotalsPostSeason, SeasonTotalsRegularSeason #' #' **SeasonTotalsRegularSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsRegularSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |Team_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsPostSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsPostSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |Team_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsAllStarSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsAllStarSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |Team_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsCollegeSeason** #' #' **CareerTotalsCollegeSeason** #' #' **SeasonTotalsShowcaseSeason** #' #' **CareerTotalsShowcaseSeason** #' #' **SeasonRankingsRegularSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |RANK_MIN |character | #' |RANK_FGM |character | #' |RANK_FGA |character | #' |RANK_FG_PCT |character | #' |RANK_FG3M |character | #' |RANK_FG3A |character | #' |RANK_FG3_PCT |character | #' |RANK_FTM |character | #' |RANK_FTA |character | #' |RANK_FT_PCT |character | #' |RANK_OREB |character | #' |RANK_DREB |character | #' |RANK_REB |character | #' |RANK_AST |character | #' |RANK_STL |character | #' |RANK_BLK |character | #' |RANK_TOV |character | #' |RANK_PTS |character | #' |RANK_EFF |character | #' #' **SeasonRankingsPostSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |RANK_MIN |character | #' |RANK_FGM |character | #' |RANK_FGA |character | #' |RANK_FG_PCT |character | #' |RANK_FG3M |character | #' |RANK_FG3A |character | #' |RANK_FG3_PCT |character | #' |RANK_FTM |character | #' |RANK_FTA |character | #' |RANK_FT_PCT |character | #' |RANK_OREB |character | #' |RANK_DREB |character | #' |RANK_REB |character | #' |RANK_AST |character | #' |RANK_STL |character | #' |RANK_BLK |character | #' |RANK_TOV |character | #' |RANK_PTS |character | #' |RANK_EFF |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playercareerstats(player_id = '1628932') #' ``` wnba_playercareerstats <- function( league_id = '10', per_mode = 'Totals', player_id = '1628932', ...){ version <- "playercareerstats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, PlayerID = player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player career stats data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API FanDuel Player Infographic** #' @name wnba_infographicfanduelplayer NULL #' @title #' **Get WNBA Stats API FanDuel Player Infographic** #' @rdname wnba_infographicfanduelplayer #' @author Saiem Gilani #' @param game_id game_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: FanDuelPlayer #' #' **FanDuelPlayer** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |JERSEY_NUM |character | #' |PLAYER_POSITION |character | #' |LOCATION |character | #' |FAN_DUEL_PTS |character | #' |WNBA_FANTASY_PTS |character | #' |USG_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Fantasy Functions #' @details #' ```r #' wnba_infographicfanduelplayer(game_id = "1022200034") #' ``` wnba_infographicfanduelplayer <- function( game_id, ...){ version <- "infographicfanduelplayer" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = game_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no FanDuel player infographic data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Fantasy Profile** #' @name wnba_playerfantasyprofile NULL #' @title #' **Get WNBA Stats API Player Fantasy Profile** #' @rdname wnba_playerfantasyprofile #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param measure_type measure_type #' @param player_id Player ID #' @param per_mode Per Mode - PerGame, Totals #' @param pace_adjust Pace Adjustment - Y/N #' @param plus_minus Plus Minus - Y/N #' @param rank Rank - Y/N #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: DaysRestModified, LastNGames, Location, Opponent, Overall #' #' **Overall** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |DD2 |character | #' |TD3 |character | #' |FAN_DUEL_PTS |character | #' |WNBA_FANTASY_PTS |character | #' #' **Location** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |DD2 |character | #' |TD3 |character | #' |FAN_DUEL_PTS |character | #' |WNBA_FANTASY_PTS |character | #' #' **LastNGames** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |DD2 |character | #' |TD3 |character | #' |FAN_DUEL_PTS |character | #' |WNBA_FANTASY_PTS |character | #' #' **DaysRestModified** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |SEASON_YEAR |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |DD2 |character | #' |TD3 |character | #' |FAN_DUEL_PTS |character | #' |WNBA_FANTASY_PTS |character | #' #' **Opponent** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |DD2 |character | #' |TD3 |character | #' |FAN_DUEL_PTS |character | #' |NBA_FANTASY_PTS|character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Fantasy Functions #' @details #' ```r #' wnba_playerfantasyprofile(player_id = '1628932') #' ``` wnba_playerfantasyprofile <- function( league_id = '10', measure_type = 'Base', pace_adjust = 'N', per_mode = 'Totals', player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerfantasyprofile" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, MeasureType = measure_type, PaceAdjust = pace_adjust, PerMode = per_mode, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player fantasy profile data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Fantasy Profile Bar Graph** #' @name wnba_playerfantasyprofilebargraph NULL #' @title #' **Get WNBA Stats API Player Fantasy Profile Bar Graph** #' @rdname wnba_playerfantasyprofilebargraph #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param player_id Player ID #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: LastFiveGamesAvg, SeasonAvg #' #' **SeasonAvg** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |FAN_DUEL_PTS |character | #' |NBA_FANTASY_PTS |character | #' |PTS |character | #' |REB |character | #' |AST |character | #' |FG3M |character | #' |FT_PCT |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |FG_PCT |character | #' #' **LastFiveGamesAvg** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |FAN_DUEL_PTS |character | #' |NBA_FANTASY_PTS |character | #' |PTS |character | #' |REB |character | #' |AST |character | #' |FG3M |character | #' |FT_PCT |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Fantasy Functions #' @details #' ```r #' wnba_playerfantasyprofilebargraph(player_id = '1628932') #' ``` wnba_playerfantasyprofilebargraph <- function( league_id = '10', player_id = '1628932', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerfantasyprofilebargraph" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PlayerID = player_id, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player fantasy profile bar graph data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Estimated Metrics** #' @name wnba_playerestimatedmetrics NULL #' @title #' **Get WNBA Stats API Player Estimated Metrics** #' @rdname wnba_playerestimatedmetrics #' @author Saiem Gilani #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerEstimatedMetrics #' #' **PlayerEstimatedMetrics** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |E_OFF_RATING |character | #' |E_DEF_RATING |character | #' |E_NET_RATING |character | #' |E_AST_RATIO |character | #' |E_OREB_PCT |character | #' |E_DREB_PCT |character | #' |E_REB_PCT |character | #' |E_TOV_PCT |character | #' |E_USG_PCT |character | #' |E_PACE |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |E_OFF_RATING_RANK |character | #' |E_DEF_RATING_RANK |character | #' |E_NET_RATING_RANK |character | #' |E_AST_RATIO_RANK |character | #' |E_OREB_PCT_RANK |character | #' |E_DREB_PCT_RANK |character | #' |E_REB_PCT_RANK |character | #' |E_TOV_PCT_RANK |character | #' |E_USG_PCT_RANK |character | #' |E_PACE_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerestimatedmetrics() #' ``` wnba_playerestimatedmetrics <- function( league_id = '10', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerestimatedmetrics" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSet$name), function(x){ data <- resp$resultSet$rowSet %>% data.frame(stringsAsFactors = FALSE) %>% dplyr::as_tibble() json_names <- resp$resultSet$headers colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSet$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player estimated metrics data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Game Log** #' @name wnba_playergamelog NULL #' @title #' **Get WNBA Stats API Player Game Log** #' @rdname wnba_playergamelog #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param player_id Player ID #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerGameLog #' #' **PlayerGameLog** #' #' #' |col_name |types | #' |:---------------|:---------| #' |SEASON_ID |character | #' |Player_ID |character | #' |Game_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |VIDEO_AVAILABLE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playergamelog(player_id = '1628932') #' ``` wnba_playergamelog <- function( date_from = '', date_to = '', league_id = '10', player_id = '1628932', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playergamelog" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, LeagueID = league_id, PlayerID = player_id, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player game log data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Game Logs** #' @name wnba_playergamelogs NULL #' @title #' **Get WNBA Stats API Player Game Logs** #' @rdname wnba_playergamelogs #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_id Player ID #' @param season Season - format 2020-21 #' @param season_segment season_segment #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerGameLogs #' #' **PlayerGameLogs** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |SEASON_YEAR |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |WNBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WWNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WWNBA_FANTASY_PTS_RANK |character | #' |VIDEO_AVAILABLE_FLAG |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playergamelogs(player_id = '1628932') #' ``` wnba_playergamelogs <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', period = 0, player_id = '1628932', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playergamelogs" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player game logs data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Game Streak Finder** #' @name wnba_playergamestreakfinder NULL #' @title #' **Get WNBA Stats API Player Game Streak Finder** #' @rdname wnba_playergamestreakfinder #' @author Saiem Gilani #' @param active_streaks_only active_streaks_only #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param draft_year draft_year #' @param draft_team_id draft_team_id #' @param draft_round draft_round #' @param draft_number draft_number #' @param et_ast et_ast #' @param et_blk et_blk #' @param et_dd et_dd #' @param et_dreb et_dreb #' @param et_fg3a et_fg3a #' @param et_fg3m et_fg3m #' @param et_fg3_pct et_fg3_pct #' @param et_fga et_fga #' @param et_fgm et_fgm #' @param et_fg_pct et_fg_pct #' @param et_fta et_fta #' @param et_ftm et_ftm #' @param et_ft_pct et_ft_pct #' @param et_minutes et_minutes #' @param et_oreb et_oreb #' @param et_pf et_pf #' @param et_pts et_pts #' @param et_reb et_reb #' @param et_stl et_stl #' @param et_td et_td #' @param et_tov et_tov #' @param game_id game_id #' @param gt_ast gt_ast #' @param gt_blk gt_blk #' @param gt_dd gt_dd #' @param gt_dreb gt_dreb #' @param gt_fg3a gt_fg3a #' @param gt_fg3m gt_fg3m #' @param gt_fg3_pct gt_fg3_pct #' @param gt_fga gt_fga #' @param gt_fgm gt_fgm #' @param gt_fg_pct gt_fg_pct #' @param gt_fta gt_fta #' @param gt_ftm gt_ftm #' @param gt_ft_pct gt_ft_pct #' @param gt_minutes gt_minutes #' @param gt_oreb gt_oreb #' @param gt_pf gt_pf #' @param gt_pts gt_pts #' @param gt_reb gt_reb #' @param gt_stl gt_stl #' @param gt_td gt_td #' @param gt_tov gt_tov #' @param league_id league_id #' @param location location #' @param lt_ast lt_ast #' @param lt_blk lt_blk #' @param lt_dd lt_dd #' @param lt_dreb lt_dreb #' @param lt_fg3a lt_fg3a #' @param lt_fg3m lt_fg3m #' @param lt_fg3_pct lt_fg3_pct #' @param lt_fga lt_fga #' @param lt_fgm lt_fgm #' @param lt_fg_pct lt_fg_pct #' @param lt_fta lt_fta #' @param lt_ftm lt_ftm #' @param lt_ft_pct lt_ft_pct #' @param lt_minutes lt_minutes #' @param lt_oreb lt_oreb #' @param lt_pf lt_pf #' @param lt_pts lt_pts #' @param lt_reb lt_reb #' @param lt_stl lt_stl #' @param lt_td lt_td #' @param lt_tov lt_tov #' @param min_games min_games #' @param outcome outcome #' @param po_round po_round #' @param player_id player_id #' @param rookie_year rookie_year #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_team_id vs_team_id #' @param years_experience years_experience #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayerGameStreakFinderResults #' #' **PlayerGameStreakFinderResults** #' #' #' |col_name |types | #' |:----------------------|:---------| #' |PLAYER_NAME_LAST_FIRST |character | #' |PLAYER_ID |character | #' |GAMESTREAK |character | #' |STARTDATE |character | #' |ENDDATE |character | #' |ACTIVESTREAK |character | #' |NUMSEASONS |character | #' |LASTSEASON |character | #' |FIRSTSEASON |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Game Finder Functions #' @details #' ```r #' wnba_playergamestreakfinder() #' ``` wnba_playergamestreakfinder <- function( active_streaks_only = '', conference = '', date_from = '', date_to = '', division = '', draft_year = '', draft_team_id = '', draft_round = '', draft_number = '', et_ast = '', et_blk = '', et_dd = '', et_dreb = '', et_fg3a = '', et_fg3m = '', et_fg3_pct = '', et_fga = '', et_fgm = '', et_fg_pct = '', et_fta = '', et_ftm = '', et_ft_pct = '', et_minutes = '', et_oreb = '', et_pf = '', et_pts = '', et_reb = '', et_stl = '', et_td = '', et_tov = '', game_id = '', gt_ast = '', gt_blk = '', gt_dd = '', gt_dreb = '', gt_fg3a = '', gt_fg3m = '', gt_fg3_pct = '', gt_fga = '', gt_fgm = '', gt_fg_pct = '', gt_fta = '', gt_ftm = '', gt_ft_pct = '', gt_minutes = '', gt_oreb = '', gt_pf = '', gt_pts = '', gt_reb = '', gt_stl = '', gt_td = '', gt_tov = '', league_id = '10', location = '', lt_ast = '', lt_blk = '', lt_dd = '', lt_dreb = '', lt_fg3a = '', lt_fg3m = '', lt_fg3_pct = '', lt_fga = '', lt_fgm = '', lt_fg_pct = '', lt_fta = '', lt_ftm = '', lt_ft_pct = '', lt_minutes = '', lt_oreb = '', lt_pf = '', lt_pts = '', lt_reb = '', lt_stl = '', lt_td = '', lt_tov = '', min_games = '', outcome = '', po_round = '', player_id = '', rookie_year = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', starter_bench = '', team_id = '', vs_conference = '', vs_division = '', vs_team_id = '', years_experience = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playergamestreakfinder" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( ActiveStreaksOnly = active_streaks_only, Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, DraftNumber = draft_number, DraftRound = draft_round, DraftTeamID = draft_team_id, DraftYear = draft_year, EqAST = et_ast, EqBLK = et_blk, EqDD = et_dd, EqDREB = et_dreb, EqFG3A = et_fg3a, EqFG3M = et_fg3m, EqFG3_PCT = et_fg3_pct, EqFGA = et_fga, EqFGM = et_fgm, EqFG_PCT = et_fg_pct, EqFTA = et_fta, EqFTM = et_ftm, EqFT_PCT = et_ft_pct, EqMINUTES = et_minutes, EqOREB = et_oreb, EqPF = et_pf, EqPTS = et_pts, EqREB = et_reb, EqSTL = et_stl, EqTD = et_td, EqTOV = et_tov, GameID = game_id, GtAST = gt_ast, GtBLK = gt_blk, GtDD = gt_dd, GtDREB = gt_dreb, GtFG3A = gt_fg3a, GtFG3M = gt_fg3m, GtFG3_PCT = gt_fg3_pct, GtFGA = gt_fga, GtFGM = gt_fgm, GtFG_PCT = gt_fg_pct, GtFTA = gt_fta, GtFTM = gt_ftm, GtFT_PCT = gt_ft_pct, GtMINUTES = gt_minutes, GtOREB = gt_oreb, GtPF = gt_pf, GtPTS = gt_pts, GtREB = gt_reb, GtSTL = gt_stl, GtTD = gt_td, GtTOV = gt_tov, LeagueID = league_id, Location = location, LtAST = lt_ast, LtBLK = lt_blk, LtDD = lt_dd, LtDREB = lt_dreb, LtFG3A = lt_fg3a, LtFG3M = lt_fg3m, LtFG3_PCT = lt_fg3_pct, LtFGA = lt_fga, LtFGM = lt_fgm, LtFG_PCT = lt_fg_pct, LtFTA = lt_fta, LtFTM = lt_ftm, LtFT_PCT = lt_ft_pct, LtMINUTES = lt_minutes, LtOREB = lt_oreb, LtPF = lt_pf, LtPTS = lt_pts, LtREB = lt_reb, LtSTL = lt_stl, LtTD = lt_td, LtTOV = lt_tov, MinGames = min_games, Outcome = outcome, PORound = po_round, PlayerID = player_id, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsTeamID = vs_team_id, YearsExperience = years_experience ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player streak finder data available for the parameters selected!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Next N Games** #' @name wnba_playernextngames NULL #' @title #' **Get WNBA Stats API Player Next N Games** #' @rdname wnba_playernextngames #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param number_of_games N in number of games #' @param player_id Player ID #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: NextNGames #' #' **NextNGames** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |GAME_ID |character | #' |GAME_DATE |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |HOME_TEAM_NAME |character | #' |VISITOR_TEAM_NAME |character | #' |HOME_TEAM_ABBREVIATION |character | #' |VISITOR_TEAM_ABBREVIATION |character | #' |HOME_TEAM_NICKNAME |character | #' |VISITOR_TEAM_NICKNAME |character | #' |GAME_TIME |character | #' |HOME_WL |character | #' |VISITOR_WL |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playernextngames(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playernextngames <- function( league_id = '10', number_of_games = 2147483647, player_id = '1628932', season = most_recent_wnba_season() - 1, season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playernextngames" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, NumberOfGames = number_of_games, PlayerID = player_id, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player next n games data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Profile V2** #' @name wnba_playerprofilev2 NULL #' @title #' **Get WNBA Stats API Player Profile V2** #' @rdname wnba_playerprofilev2 #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param player_id Player ID #' @param per_mode Season - format 2020-21 #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: CareerHighs, CareerTotalsAllStarSeason, CareerTotalsCollegeSeason, CareerTotalsPostSeason, CareerTotalsPreseason, #' CareerTotalsRegularSeason, NextGame, SeasonHighs, SeasonRankingsPostSeason, SeasonRankingsRegularSeason, SeasonTotalsAllStarSeason, SeasonTotalsCollegeSeason, #' SeasonTotalsPostSeason, SeasonTotalsPreseason, SeasonTotalsRegularSeason #' #' **SeasonTotalsRegularSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsRegularSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsPostSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsPostSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsAllStarSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsAllStarSeason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonTotalsCollegeSeason** #' #' **CareerTotalsCollegeSeason** #' #' **SeasonTotalsPreseason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **CareerTotalsPreseason** #' #' #' |col_name |types | #' |:---------|:---------| #' |PLAYER_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |GP |character | #' |GS |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' **SeasonRankingsRegularSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |RANK_MIN |character | #' |RANK_FGM |character | #' |RANK_FGA |character | #' |RANK_FG_PCT |character | #' |RANK_FG3M |character | #' |RANK_FG3A |character | #' |RANK_FG3_PCT |character | #' |RANK_FTM |character | #' |RANK_FTA |character | #' |RANK_FT_PCT |character | #' |RANK_OREB |character | #' |RANK_DREB |character | #' |RANK_REB |character | #' |RANK_AST |character | #' |RANK_STL |character | #' |RANK_BLK |character | #' |RANK_TOV |character | #' |RANK_PTS |character | #' |RANK_EFF |character | #' #' **SeasonRankingsPostSeason** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |PLAYER_ID |character | #' |SEASON_ID |character | #' |LEAGUE_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |PLAYER_AGE |character | #' |GP |character | #' |GS |character | #' |RANK_MIN |character | #' |RANK_FGM |character | #' |RANK_FGA |character | #' |RANK_FG_PCT |character | #' |RANK_FG3M |character | #' |RANK_FG3A |character | #' |RANK_FG3_PCT |character | #' |RANK_FTM |character | #' |RANK_FTA |character | #' |RANK_FT_PCT |character | #' |RANK_OREB |character | #' |RANK_DREB |character | #' |RANK_REB |character | #' |RANK_AST |character | #' |RANK_STL |character | #' |RANK_BLK |character | #' |RANK_TOV |character | #' |RANK_PTS |character | #' |RANK_EFF |character | #' #' **SeasonHighs** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |PLAYER_ID |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |VS_TEAM_ID |character | #' |VS_TEAM_CITY |character | #' |VS_TEAM_NAME |character | #' |VS_TEAM_ABBREVIATION |character | #' |STAT |character | #' |STAT_VALUE |character | #' |STAT_ORDER |character | #' |DATE_EST |character | #' #' **CareerHighs** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |PLAYER_ID |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |VS_TEAM_ID |character | #' |VS_TEAM_CITY |character | #' |VS_TEAM_NAME |character | #' |VS_TEAM_ABBREVIATION |character | #' |STAT |character | #' |STAT_VALUE |character | #' |STAT_ORDER |character | #' |DATE_EST |character | #' #' **NextGame** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |GAME_ID |character | #' |GAME_DATE |character | #' |GAME_TIME |character | #' |LOCATION |character | #' |PLAYER_TEAM_ID |character | #' |PLAYER_TEAM_CITY |character | #' |PLAYER_TEAM_NICKNAME |character | #' |PLAYER_TEAM_ABBREVIATION |character | #' |VS_TEAM_ID |character | #' |VS_TEAM_CITY |character | #' |VS_TEAM_NICKNAME |character | #' |VS_TEAM_ABBREVIATION |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerprofilev2(player_id = '1628932') #' ``` wnba_playerprofilev2 <- function( league_id = '', per_mode = 'Totals', player_id = '1628932', ...){ version <- "playerprofilev2" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, PlayerID = player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player profile v2 data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player vs Player** #' @name wnba_playervsplayer NULL #' @title #' **Get WNBA Stats API Player vs Player** #' @rdname wnba_playervsplayer #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id Player ID #' @param plus_minus plus_minus #' @param rank rank #' @param season Season - format 2020-21 #' @param season_segment season_segment #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_player_id vs_player_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OnOffCourt, Overall, PlayerInfo, ShotAreaOffCourt, #' ShotAreaOnCourt, ShotAreaOverall, ShotDistanceOffCourt, ShotDistanceOnCourt, #' ShotDistanceOverall, VsPlayerInfo #' #' **Overall** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |WNBA_FANTASY_PTS |character | #' #' **OnOffCourt** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |WNBA_FANTASY_PTS |character | #' #' **ShotDistanceOverall** #' #' #' |col_name |types | #' |:-----------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotDistanceOnCourt** #' #' #' |col_name |types | #' |:--------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotDistanceOffCourt** #' #' #' |col_name |types | #' |:--------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOverall** #' #' #' |col_name |types | #' |:-----------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOnCourt** #' #' #' |col_name |types | #' |:--------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOffCourt** #' #' #' |col_name |types | #' |:--------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **PlayerInfo** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |PERSON_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |DISPLAY_FIRST_LAST |character | #' |DISPLAY_LAST_COMMA_FIRST |character | #' |DISPLAY_FI_LAST |character | #' |BIRTHDATE |character | #' |SCHOOL |character | #' |COUNTRY |character | #' |LAST_AFFILIATION |character | #' #' **VsPlayerInfo** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |PERSON_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |DISPLAY_FIRST_LAST |character | #' |DISPLAY_LAST_COMMA_FIRST |character | #' |DISPLAY_FI_LAST |character | #' |BIRTHDATE |character | #' |SCHOOL |character | #' |COUNTRY |character | #' |LAST_AFFILIATION |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playervsplayer(player_id = '1628932', vs_player_id = '1629488') #' ``` wnba_playervsplayer <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', vs_conference = '', vs_division = '', vs_player_id = '1629488', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playervsplayer" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, VsConference = vs_conference, VsDivision = vs_division, VsPlayerID = vs_player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player vs player data unavailable for the parameters selected!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Compare** #' @name wnba_playercompare NULL #' @title #' **Get WNBA Stats API Player Compare** #' @rdname wnba_playercompare #' @author Saiem Gilani #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id_list Player ID #' @param plus_minus plus_minus #' @param rank rank #' @param season Season - format 2020-21 #' @param season_segment season_segment #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_player_id_list vs_player_id_list #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Individual, OverallCompare #' #' **OverallCompare** #' #' #' |col_name |types | #' |:-----------|:---------| #' |GROUP_SET |character | #' |DESCRIPTION |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' #' **Individual** #' #' #' |col_name |types | #' |:-----------|:---------| #' |GROUP_SET |character | #' |DESCRIPTION |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playercompare(player_id_list = '100720,202250,204319,1627668,1628931', vs_player_id_list = '202252,203399,1631022,1628878,204333') #' ``` wnba_playercompare <- function( conference = '', date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id_list = '100720,202250,204319,1627668,1628931', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', vs_player_id_list = '202252,203399,1631022,1628878,204333', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playercompare" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( Conference = conference, DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerIDList = URLencode(player_id_list), PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division, VsPlayerIDList = URLencode(vs_player_id_list) ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player comparison data unavailable for the parameters selected!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_player.R
## Player Dashboard parameters are the same #' **Get WNBA Stats API Player Dashboard by Clutch Splits** #' @name wnba_playerdashboardbyclutch NULL #' @title #' **Get WNBA Stats API Player Dashboard by Clutch Splits** #' @rdname wnba_playerdashboardbyclutch #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Last10Sec3Point2PlayerDashboard, #' Last10Sec3PointPlayerDashboard, Last1Min5PointPlayerDashboard, #' Last1MinPlusMinus5PointPlayerDashboard, Last30Sec3Point2PlayerDashboard, #' Last30Sec3PointPlayerDashboard, Last3Min5PointPlayerDashboard, #' Last3MinPlusMinus5PointPlayerDashboard, Last5Min5PointPlayerDashboard, #' Last5MinPlusMinus5PointPlayerDashboard, OverallPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last5Min5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last3Min5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last1Min5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last30Sec3PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last10Sec3PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last5MinPlusMinus5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last3MinPlusMinus5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last1MinPlusMinus5PointPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last30Sec3Point2PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last10Sec3Point2PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Clutch Functions #' @details #' ```r #' wnba_playerdashboardbyclutch(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbyclutch <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbyclutch" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player dashboard by clutch splits data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by Game Splits** #' @name wnba_playerdashboardbygamesplits NULL #' @title #' **Get WNBA Stats API Player Dashboard by Game Splits** #' @rdname wnba_playerdashboardbygamesplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ByActualMarginPlayerDashboard, #' ByHalfPlayerDashboard, ByPeriodPlayerDashboard, ByScoreMarginPlayerDashboard, #' OverallPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ByHalfPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ByPeriodPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ByScoreMarginPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ByActualMarginPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbygamesplits(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbygamesplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbygamesplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or player dashboard by game splits data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by General Splits** #' @name wnba_playerdashboardbygeneralsplits NULL #' @title #' **Get WNBA Stats API Player Dashboard by General Splits** #' @rdname wnba_playerdashboardbygeneralsplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: DaysRestPlayerDashboard, LocationPlayerDashboard, #' MonthPlayerDashboard, OverallPlayerDashboard, PrePostAllStarPlayerDashboard, #' StartingPosition, WinsLossesPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **LocationPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **WinsLossesPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **MonthPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **PrePostAllStarPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **StartingPosition** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **DaysRestPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbygeneralsplits(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbygeneralsplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbygeneralsplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard by general splits data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by Last N Games** #' @name wnba_playerdashboardbylastngames NULL #' @title #' **Get WNBA Stats API Player Dashboard by Last N Games** #' @rdname wnba_playerdashboardbylastngames #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: GameNumberPlayerDashboard, Last10PlayerDashboard, #' Last15PlayerDashboard, Last20PlayerDashboard, #' Last5PlayerDashboard, OverallPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last5PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last10PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last15PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **Last20PlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **GameNumberPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbylastngames(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbylastngames <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbylastngames" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard by last n games data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by Opponent** #' @name wnba_playerdashboardbyopponent NULL #' @title #' **Get WNBA Stats API Player Dashboard by Opponent** #' @rdname wnba_playerdashboardbyopponent #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ConferencePlayerDashboard, #' DivisionPlayerDashboard, OpponentPlayerDashboard, OverallPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ConferencePlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |WBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **DivisionPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **OpponentPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbyopponent(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbyopponent <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbyopponent" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard by opponent data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by Shooting Splits** #' @name wnba_playerdashboardbyshootingsplits NULL #' @title #' **Get WNBA Stats API Player Dashboard by Shooting Splits** #' @rdname wnba_playerdashboardbyshootingsplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: AssistedBy, AssitedShotPlayerDashboard, #' OverallPlayerDashboard, Shot5FTPlayerDashboard, Shot8FTPlayerDashboard, #' ShotAreaPlayerDashboard, ShotTypePlayerDashboard, ShotTypeSummaryPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **Shot5FTPlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **Shot8FTPlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **ShotAreaPlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **AssitedShotPlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **ShotTypeSummaryPlayerDashboard** #' #' #' |col_name |types | #' |:------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' #' **ShotTypePlayerDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **AssistedBy** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @family WNBA Shooting Functions #' @details #' ```r #' wnba_playerdashboardbyshootingsplits(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbyshootingsplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbyshootingsplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard by shooting splits data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard by Team Performance** #' @name wnba_playerdashboardbyteamperformance NULL #' @title #' **Get WNBA Stats API Player Dashboard by Team Performance** #' @rdname wnba_playerdashboardbyteamperformance #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OverallPlayerDashboard, #' PointsScoredPlayerDashboard, PointsAgainstPlayerDashboard, #' ScoreDifferentialPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ScoreDifferentialPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **PointsScoredPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **PontsAgainstPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbyteamperformance(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbyteamperformance <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbyteamperformance" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard by team performance data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Dashboard Year over Year** #' @name wnba_playerdashboardbyyearoveryear NULL #' @title #' **Get WNBA Stats API Player Dashboard Year over Year** #' @rdname wnba_playerdashboardbyyearoveryear #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id player_id #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ByYearPlayerDashboard, OverallPlayerDashboard #' #' **OverallPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |MAX_GAME_DATE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **ByYearPlayerDashboard** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |MAX_GAME_DATE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Player Functions #' @details #' ```r #' wnba_playerdashboardbyyearoveryear(player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_playerdashboardbyyearoveryear <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '1628932', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', shot_clock_range = '', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "playerdashboardbyyearoveryear" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player dashboard year-over-year data available for {player_id}!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_player_dash.R
#' **Get WNBA Stats API All Players** #' @name wnba_commonallplayers NULL #' @title #' **Get WNBA Stats API All Players** #' @rdname wnba_commonallplayers #' @author Saiem Gilani #' @param is_only_current_season is_only_current_season #' @param league_id league_id #' @param season season #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: CommonAllPlayers #' #' **CommonAllPlayers** #' #' #' |col_name |types | #' |:------------------------|:---------| #' |PERSON_ID |character | #' |DISPLAY_LAST_COMMA_FIRST |character | #' |DISPLAY_FIRST_LAST |character | #' |ROSTERSTATUS |character | #' |FROM_YEAR |character | #' |TO_YEAR |character | #' |PLAYERCODE |character | #' |PLAYER_SLUG |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CODE |character | #' |TEAM_SLUG |character | #' |IS_NBA_ASSIGNED |character | #' |NBA_ASSIGNED_TEAM_ID |character | #' |GAMES_PLAYED_FLAG |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Roster Functions #' @details #' ```r #' wnba_commonallplayers(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_commonallplayers <- function( is_only_current_season = 0, league_id = '10', season = most_recent_wnba_season() - 1, ...){ version <- "commonallplayers" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( IsOnlyCurrentSeason = is_only_current_season, LeagueID = league_id, Season = season ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or common all players data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Player Info** #' @name wnba_commonplayerinfo NULL #' @title #' **Get WNBA Stats API Player Info** #' @rdname wnba_commonplayerinfo #' @author Saiem Gilani #' @param league_id league_id #' @param player_id player_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: CommonPlayerInfo, PlayerHeadlineStats, #' AvailableSeasons #' #' **CommonPlayerInfo** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |PERSON_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |DISPLAY_FIRST_LAST |character | #' |DISPLAY_LAST_COMMA_FIRST |character | #' |DISPLAY_FI_LAST |character | #' |PLAYER_SLUG |character | #' |BIRTHDATE |character | #' |SCHOOL |character | #' |COUNTRY |character | #' |LAST_AFFILIATION |character | #' |HEIGHT |character | #' |WEIGHT |character | #' |SEASON_EXP |character | #' |JERSEY |character | #' |POSITION |character | #' |ROSTERSTATUS |character | #' |GAMES_PLAYED_CURRENT_SEASON_FLAG |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CODE |character | #' |TEAM_CITY |character | #' |PLAYERCODE |character | #' |FROM_YEAR |character | #' |TO_YEAR |character | #' |DLEAGUE_FLAG |character | #' |NBA_FLAG |character | #' |GAMES_PLAYED_FLAG |character | #' |DRAFT_YEAR |character | #' |DRAFT_ROUND |character | #' |DRAFT_NUMBER |character | #' |GREATEST_75_FLAG |character | #' #' **PlayerHeadlineStats** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TimeFrame |character | #' |PTS |character | #' |AST |character | #' |REB |character | #' |ALL_STAR_APPEARANCES |character | #' #' **AvailableSeasons** #' #' #' |col_name |types | #' |:---------|:---------| #' |SEASON_ID |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Roster Functions #' @details #' ```r #' wnba_commonplayerinfo(league_id = '10', player_id = '1628932') #' ``` wnba_commonplayerinfo <- function( league_id = '10', player_id = '1628932', ...){ version <- "commonplayerinfo" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PlayerID = player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or common player info data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Playoff Series** #' @name wnba_commonplayoffseries NULL #' @title #' **Get WNBA Stats API Playoff Series** #' @rdname wnba_commonplayoffseries #' @author Saiem Gilani #' @param league_id league_id #' @param season season #' @param series_id series_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayoffSeries #' #' **PlayoffSeries** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GAME_ID |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |SERIES_ID |character | #' |GAME_NUM |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @details #' ```r #' wnba_commonplayoffseries(league_id = '10', season = most_recent_wnba_season() - 2) #' ``` wnba_commonplayoffseries <- function( league_id = '10', season = most_recent_wnba_season() - 2, series_id = '', ...){ version <- "commonplayoffseries" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, SeriesID = series_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or common playoff series data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Roster** #' @name wnba_commonteamroster NULL #' @title #' **Get WNBA Stats API Team Roster** #' @rdname wnba_commonteamroster #' @author Saiem Gilani #' @param league_id league_id #' @param season season #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Coaches, CommonTeamRoster #' #' **CommonTeamRoster** #' #' #' |col_name |types | #' |:------------|:---------| #' |TeamID |character | #' |SEASON |character | #' |LeagueID |character | #' |PLAYER |character | #' |NICKNAME |character | #' |PLAYER_SLUG |character | #' |NUM |character | #' |POSITION |character | #' |HEIGHT |character | #' |WEIGHT |character | #' |BIRTH_DATE |character | #' |AGE |character | #' |EXP |character | #' |SCHOOL |character | #' |PLAYER_ID |character | #' |HOW_ACQUIRED |character | #' #' **Coaches** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |SEASON |character | #' |COACH_ID |character | #' |FIRST_NAME |character | #' |LAST_NAME |character | #' |COACH_NAME |character | #' |IS_ASSISTANT |character | #' |COACH_TYPE |character | #' |SORT_SEQUENCE |character | #' |SUB_SORT_SEQUENCE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Roster Functions #' @details #' ```r #' wnba_commonteamroster(season = most_recent_wnba_season() - 1, team_id = '1611661317') #' ``` wnba_commonteamroster <- function( league_id = '10', season = most_recent_wnba_season() - 1, team_id = '1611661317', ...){ version <- "commonteamroster" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or common team roster data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_roster.R
#' **Get WNBA Stats API Season Schedule** #' @name wnba_schedule NULL #' @title #' **Get WNBA Stats API Season Schedule** #' @rdname wnba_schedule #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param season Season #' @param ... Additional arguments passed to an underlying function like httr. #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @return Returns a tibble with the following columns: #' #' |col_name |types | #' |:------------------|:---------| #' |game_date |character | #' |game_id |character | #' |game_code |character | #' |game_status |integer | #' |game_status_text |character | #' |game_sequence |integer | #' |game_date_est |character | #' |game_time_est |character | #' |game_date_time_est |character | #' |game_date_utc |character | #' |game_time_utc |character | #' |game_date_time_utc |character | #' |away_team_time |character | #' |home_team_time |character | #' |day |character | #' |month_num |integer | #' |week_number |integer | #' |week_name |character | #' |if_necessary |character | #' |series_game_number |character | #' |series_text |character | #' |arena_name |character | #' |arena_state |character | #' |arena_city |character | #' |postponed_status |character | #' |branch_link |character | #' |game_subtype |character | #' |home_team_id |integer | #' |home_team_name |character | #' |home_team_city |character | #' |home_team_tricode |character | #' |home_team_slug |character | #' |home_team_wins |integer | #' |home_team_losses |integer | #' |home_team_score |integer | #' |home_team_seed |integer | #' |away_team_id |integer | #' |away_team_name |character | #' |away_team_city |character | #' |away_team_tricode |character | #' |away_team_slug |character | #' |away_team_wins |integer | #' |away_team_losses |integer | #' |away_team_score |integer | #' |away_team_seed |integer | #' |season |character | #' |league_id |character | #' #' @export #' @family WNBA Schedule Functions #' @details #' ```r #' wnba_schedule(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_schedule <- function( league_id = '10', season = most_recent_wnba_season() - 1, ...){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) version <- "scheduleleaguev2" full_url <- wnba_endpoint(version) params <- list( LeagueID = league_id, Season = season ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) league_sched <- resp %>% purrr::pluck("leagueSchedule") games <- league_sched %>% purrr::pluck("gameDates") %>% tidyr::unnest("games") %>% tidyr::unnest("awayTeam", names_sep = "_") %>% tidyr::unnest("homeTeam", names_sep = "_") %>% dplyr::select(-dplyr::any_of(c("broadcasters", "pointsLeaders"))) %>% janitor::clean_names() colnames(games) <- gsub('team_team', 'team', colnames(games)) games$game_id <- unlist(purrr::map(games$game_id,function(x){ pad_id(x) })) games$season <- league_sched$seasonYear games$league_id <- league_sched$leagueId games <- games %>% dplyr::mutate( season_type_id = substr(.data$game_id, 3, 3), season_type_description = dplyr::case_when( .data$season_type_id == 1 ~ "Pre-Season", .data$season_type_id == 2 ~ "Regular Season", .data$season_type_id == 3 ~ "All-Star", .data$season_type_id == 4 ~ "Playoffs", .data$season_type_id == 5 ~ "Play-In Game"), game_date = lubridate::ymd(substring(.data$game_date,1,10))) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league schedule data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(games) } #' **Get WNBA Stats API Scoreboard** #' @name wnba_scoreboard NULL #' @title #' **Get WNBA Stats API Scoreboard** #' @rdname wnba_scoreboard #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param game_date Game Date, format: 2022/05/17 #' @param day_offset Day Offset (integer 0,-1) #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Available, EastConfStandingsByDay, #' GameHeader, LastMeeting, LineScore, SeriesStandings, WestConfStandingsByDay #' #' **GameHeader** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |GAME_STATUS_ID |character | #' |GAME_STATUS_TEXT |character | #' |GAMECODE |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |SEASON |character | #' |LIVE_PERIOD |character | #' |LIVE_PC_TIME |character | #' |NATL_TV_BROADCASTER_ABBREVIATION |character | #' |LIVE_PERIOD_TIME_BCAST |character | #' |WH_STATUS |character | #' #' **LineScore** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY_NAME |character | #' |TEAM_WINS_LOSSES |character | #' |PTS_QTR1 |character | #' |PTS_QTR2 |character | #' |PTS_QTR3 |character | #' |PTS_QTR4 |character | #' |PTS_OT1 |character | #' |PTS_OT2 |character | #' |PTS_OT3 |character | #' |PTS_OT4 |character | #' |PTS_OT5 |character | #' |PTS_OT6 |character | #' |PTS_OT7 |character | #' |PTS_OT8 |character | #' |PTS_OT9 |character | #' |PTS_OT10 |character | #' |PTS |character | #' |FG_PCT |character | #' |FT_PCT |character | #' |FG3_PCT |character | #' |AST |character | #' |REB |character | #' |TOV |character | #' #' **SeriesStandings** #' #' #' |col_name |types | #' |:----------------|:---------| #' |GAME_ID |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |GAME_DATE_EST |character | #' |HOME_TEAM_WINS |character | #' |HOME_TEAM_LOSSES |character | #' |SERIES_LEADER |character | #' #' **LastMeeting** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_ID |character | #' |LAST_GAME_ID |character | #' |LAST_GAME_DATE_EST |character | #' |LAST_GAME_HOME_TEAM_ID |character | #' |LAST_GAME_HOME_TEAM_CITY |character | #' |LAST_GAME_HOME_TEAM_NAME |character | #' |LAST_GAME_HOME_TEAM_ABBREVIATION |character | #' |LAST_GAME_HOME_TEAM_POINTS |character | #' |LAST_GAME_VISITOR_TEAM_ID |character | #' |LAST_GAME_VISITOR_TEAM_CITY |character | #' |LAST_GAME_VISITOR_TEAM_NAME |character | #' |LAST_GAME_VISITOR_TEAM_CITY1 |character | #' |LAST_GAME_VISITOR_TEAM_POINTS |character | #' #' **EastConfStandingsByDay** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |LEAGUE_ID |character | #' |SEASON_ID |character | #' |STANDINGSDATE |character | #' |CONFERENCE |character | #' |TEAM |character | #' |G |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |HOME_RECORD |character | #' |ROAD_RECORD |character | #' #' **WestConfStandingsByDay** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |LEAGUE_ID |character | #' |SEASON_ID |character | #' |STANDINGSDATE |character | #' |CONFERENCE |character | #' |TEAM |character | #' |G |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |HOME_RECORD |character | #' |ROAD_RECORD |character | #' #' **Available** #' #' #' |col_name |types | #' |:------------|:---------| #' |GAME_ID |character | #' |PT_AVAILABLE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Schedule Functions #' @details #' ```r #' wnba_scoreboard(league_id = '10', game_date = '2022-07-20') #' ``` wnba_scoreboard <- function( league_id = '10', game_date = '2022-07-20', day_offset = 0, ...){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) version <- "scoreboard" full_url <- wnba_endpoint(version) params <- list( LeagueID = league_id, GameDate = game_date, DayOffset = day_offset ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoreboard data for {game_date} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Scoreboard V2** #' @name wnba_scoreboardv2 NULL #' @title #' **Get WNBA Stats API Scoreboard V2** #' @rdname wnba_scoreboardv2 #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WWNBA, '20': G-League #' @param game_date Game Date, format: 2022/05/17 #' @param day_offset Day Offset (integer 0,-1) #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Available, EastConfStandingsByDay, #' GameHeader, LastMeeting, LineScore, SeriesStandings, TeamLeaders, #' TicketLinks, WestConfStandingsByDay, WinProbability #' #' #' **GameHeader** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |GAME_STATUS_ID |character | #' |GAME_STATUS_TEXT |character | #' |GAMECODE |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |SEASON |character | #' |LIVE_PERIOD |character | #' |LIVE_PC_TIME |character | #' |NATL_TV_BROADCASTER_ABBREVIATION |character | #' |HOME_TV_BROADCASTER_ABBREVIATION |character | #' |AWAY_TV_BROADCASTER_ABBREVIATION |character | #' |LIVE_PERIOD_TIME_BCAST |character | #' |ARENA_NAME |character | #' |WH_STATUS |character | #' |WNBA_COMMISSIONER_FLAG |character | #' #' **LineScore** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_DATE_EST |character | #' |GAME_SEQUENCE |character | #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CITY_NAME |character | #' |TEAM_NAME |character | #' |TEAM_WINS_LOSSES |character | #' |PTS_QTR1 |character | #' |PTS_QTR2 |character | #' |PTS_QTR3 |character | #' |PTS_QTR4 |character | #' |PTS_OT1 |character | #' |PTS_OT2 |character | #' |PTS_OT3 |character | #' |PTS_OT4 |character | #' |PTS_OT5 |character | #' |PTS_OT6 |character | #' |PTS_OT7 |character | #' |PTS_OT8 |character | #' |PTS_OT9 |character | #' |PTS_OT10 |character | #' |PTS |character | #' |FG_PCT |character | #' |FT_PCT |character | #' |FG3_PCT |character | #' |AST |character | #' |REB |character | #' |TOV |character | #' #' **SeriesStandings** #' #' #' |col_name |types | #' |:----------------|:---------| #' |GAME_ID |character | #' |HOME_TEAM_ID |character | #' |VISITOR_TEAM_ID |character | #' |GAME_DATE_EST |character | #' |HOME_TEAM_WINS |character | #' |HOME_TEAM_LOSSES |character | #' |SERIES_LEADER |character | #' #' **LastMeeting** #' #' #' |col_name |types | #' |:--------------------------------|:---------| #' |GAME_ID |character | #' |LAST_GAME_ID |character | #' |LAST_GAME_DATE_EST |character | #' |LAST_GAME_HOME_TEAM_ID |character | #' |LAST_GAME_HOME_TEAM_CITY |character | #' |LAST_GAME_HOME_TEAM_NAME |character | #' |LAST_GAME_HOME_TEAM_ABBREVIATION |character | #' |LAST_GAME_HOME_TEAM_POINTS |character | #' |LAST_GAME_VISITOR_TEAM_ID |character | #' |LAST_GAME_VISITOR_TEAM_CITY |character | #' |LAST_GAME_VISITOR_TEAM_NAME |character | #' |LAST_GAME_VISITOR_TEAM_CITY1 |character | #' |LAST_GAME_VISITOR_TEAM_POINTS |character | #' #' **EastConfStandingsByDay** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |LEAGUE_ID |character | #' |SEASON_ID |character | #' |STANDINGSDATE |character | #' |CONFERENCE |character | #' |TEAM |character | #' |G |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |HOME_RECORD |character | #' |ROAD_RECORD |character | #' #' **WestConfStandingsByDay** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |LEAGUE_ID |character | #' |SEASON_ID |character | #' |STANDINGSDATE |character | #' |CONFERENCE |character | #' |TEAM |character | #' |G |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |HOME_RECORD |character | #' |ROAD_RECORD |character | #' #' **Available** #' #' #' |col_name |types | #' |:------------|:---------| #' |GAME_ID |character | #' |PT_AVAILABLE |character | #' #' **TeamLeaders** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GAME_ID |character | #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NICKNAME |character | #' |TEAM_ABBREVIATION |character | #' |PTS_PLAYER_ID |character | #' |PTS_PLAYER_NAME |character | #' |PTS |character | #' |REB_PLAYER_ID |character | #' |REB_PLAYER_NAME |character | #' |REB |character | #' |AST_PLAYER_ID |character | #' |AST_PLAYER_NAME |character | #' |AST |character | #' #' **TicketLinks** #' #' **WinProbability** #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Schedule Functions #' @details #' ```r #' wnba_scoreboardv2(league_id = '10', game_date = '2022-07-20') #' ``` wnba_scoreboardv2 <- function( league_id = '10', game_date = '2022-07-20', day_offset = 0, ...){ version <- "scoreboardv2" full_url <- wnba_endpoint(version) params <- list( LeagueID = league_id, GameDate = game_date, DayOffset = day_offset ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoreboardv2 data for {game_date} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Scoreboard V3** #' @name wnba_scoreboardv3 NULL #' @title #' **Get WNBA Stats API Scoreboard V3** #' @rdname wnba_scoreboardv3 #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param game_date Game Date #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a tibble with the following scoreboard data: #' #' |col_name |types | #' |:------------------------------|:----------| #' |game_id |character | #' |game_code |character | #' |game_status |integer | #' |game_status_text |character | #' |game_date |character | #' |game_time_utc |character | #' |game_et |character | #' |home_team_id |integer | #' |home_team_name |character | #' |home_team_city |character | #' |home_team_tricode |character | #' |home_team_slug |character | #' |away_team_id |integer | #' |away_team_name |character | #' |away_team_city |character | #' |away_team_tricode |character | #' |away_team_slug |character | #' |period |integer | #' |game_clock |character | #' |regulation_periods |integer | #' |series_game_number |character | #' |series_text |character | #' |if_necessary |logical | #' |series_conference |character | #' |po_round_desc |character | #' |game_subtype |character | #' |game_home_leaders_person_id |integer | #' |game_home_leaders_name |character | #' |game_home_leaders_player_slug |character | #' |game_home_leaders_jersey_num |character | #' |game_home_leaders_position |character | #' |game_home_leaders_team_tricode |character | #' |game_home_leaders_points |integer | #' |game_home_leaders_rebounds |integer | #' |game_home_leaders_assists |integer | #' |game_away_leaders_person_id |integer | #' |game_away_leaders_name |character | #' |game_away_leaders_player_slug |character | #' |game_away_leaders_jersey_num |character | #' |game_away_leaders_position |character | #' |game_away_leaders_team_tricode |character | #' |game_away_leaders_points |integer | #' |game_away_leaders_rebounds |integer | #' |game_away_leaders_assists |integer | #' |team_home_leaders_person_id |integer | #' |team_home_leaders_name |character | #' |team_home_leaders_player_slug |character | #' |team_home_leaders_jersey_num |character | #' |team_home_leaders_position |character | #' |team_home_leaders_team_tricode |character | #' |team_home_leaders_points |numeric | #' |team_home_leaders_rebounds |numeric | #' |team_home_leaders_assists |numeric | #' |team_away_leaders_person_id |integer | #' |team_away_leaders_name |character | #' |team_away_leaders_player_slug |character | #' |team_away_leaders_jersey_num |character | #' |team_away_leaders_position |character | #' |team_away_leaders_team_tricode |character | #' |team_away_leaders_points |numeric | #' |team_away_leaders_rebounds |numeric | #' |team_away_leaders_assists |numeric | #' |team_season_leaders_flag |integer | #' |home_wins |integer | #' |home_losses |integer | #' |home_score |integer | #' |home_seed |integer | #' |home_in_bonus |logical | #' |home_timeouts_remaining |integer | #' |home_periods |list | #' |away_wins |integer | #' |away_losses |integer | #' |away_score |integer | #' |away_seed |integer | #' |away_in_bonus |logical | #' |away_timeouts_remaining |integer | #' |away_periods |list | #' |league_id |character | #' |league |character | #' |broadcasters |data.frame | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Schedule Functions #' @details #' ```r #' wnba_scoreboardv3(league_id = '10', game_date = '2022-06-26') #' ``` wnba_scoreboardv3 <- function( league_id = '10', game_date = '2022-06-26', ...){ version <- "scoreboardv3" full_url <- wnba_endpoint(version) params <- list( LeagueID = league_id, GameDate = game_date ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) scoreboard <- resp %>% purrr::pluck("scoreboard") games <- scoreboard %>% purrr::pluck("games") %>% tidyr::unnest("homeTeam", names_sep = '_') %>% tidyr::unnest("awayTeam", names_sep = '_') %>% tidyr::unnest("gameLeaders", names_sep = '_') %>% tidyr::unnest("gameLeaders_homeLeaders", names_sep = '_') %>% tidyr::unnest("gameLeaders_awayLeaders", names_sep = '_') %>% tidyr::unnest("teamLeaders", names_sep = '_') %>% tidyr::unnest("teamLeaders_homeLeaders", names_sep = '_') %>% tidyr::unnest("teamLeaders_awayLeaders", names_sep = '_') colnames(games) <- gsub("gameLeaders","game", colnames(games)) colnames(games) <- gsub("teamLeaders","team", colnames(games)) colnames(games) <- gsub("homeTeam","home", colnames(games)) colnames(games) <- gsub("awayTeam","away", colnames(games)) games <- games %>% janitor::clean_names() %>% dplyr::mutate( game_date = game_date, league_id = league_id, league = dplyr::case_when( league_id == '00' ~ 'NBA', league_id == '10' ~ 'WNBA', league_id == '20' ~ 'G-League', TRUE ~ 'NBA')) %>% dplyr::select( "game_id", "game_code", "game_status", "game_status_text", "game_date", "game_time_utc", "game_et", dplyr::starts_with("home_team"), dplyr::starts_with("away_team"), tidyr::everything()) %>% dplyr::relocate("broadcasters", .after = dplyr::last_col()) %>% make_wehoop_data("WNBA Scoreboard V3 Information from WNBA.com", Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no scoreboard v3 data for {game_date} available!")) }, warning = function(w) { }, finally = { } ) return(games) } #' **Get WNBA Stats API Today's Scoreboard** #' @name wnba_todays_scoreboard NULL #' @title #' **Get WNBA Stats API Today's Scoreboard** #' @rdname wnba_todays_scoreboard #' @author Saiem Gilani #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a data frame with the following columns: #' #' |col_name |types | #' |:-------------------------|:---------| #' |game_id |character | #' |game_code |character | #' |game_status |integer | #' |game_status_text |character | #' |period |integer | #' |game_clock |character | #' |game_time_utc |character | #' |game_et |character | #' |regulation_periods |integer | #' |series_game_number |logical | #' |series_text |logical | #' |home_team_id |integer | #' |home_team_name |character | #' |home_team_city |character | #' |home_team_tricode |character | #' |home_wins |integer | #' |home_losses |integer | #' |home_score |integer | #' |home_in_bonus |character | #' |home_timeouts_remaining |integer | #' |home_periods |list | #' |away_team_id |integer | #' |away_team_name |character | #' |away_team_city |character | #' |away_team_tricode |character | #' |away_wins |integer | #' |away_losses |integer | #' |away_score |integer | #' |away_in_bonus |character | #' |away_timeouts_remaining |integer | #' |away_periods |list | #' |home_leaders_person_id |integer | #' |home_leaders_name |character | #' |home_leaders_jersey_num |character | #' |home_leaders_position |character | #' |home_leaders_team_tricode |character | #' |home_leaders_player_slug |character | #' |home_leaders_points |integer | #' |home_leaders_rebounds |integer | #' |home_leaders_assists |integer | #' |away_leaders_person_id |integer | #' |away_leaders_name |character | #' |away_leaders_jersey_num |character | #' |away_leaders_position |character | #' |away_leaders_team_tricode |character | #' |away_leaders_player_slug |character | #' |away_leaders_points |integer | #' |away_leaders_rebounds |integer | #' |away_leaders_assists |integer | #' |pb_odds_team |logical | #' |pb_odds_odds |numeric | #' |pb_odds_suspended |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Schedule Functions #' @family WNBA Live Functions #' @details #' ```r #' wnba_todays_scoreboard() #' ``` wnba_todays_scoreboard <- function( ...){ old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) tryCatch( expr = { full_url <- "https://cdn.nba.com/static/json/liveData/scoreboard/todaysScoreboard_10.json" res <- rvest::session(url = full_url, ..., httr::timeout(60)) resp <- res$response %>% httr::content(as = "text", encoding = "UTF-8") %>% jsonlite::fromJSON() scoreboard <- resp %>% purrr::pluck("scoreboard") games <- scoreboard %>% purrr::pluck("games") %>% tidyr::unnest("homeTeam", names_sep = '_') %>% tidyr::unnest("awayTeam", names_sep = '_') %>% tidyr::unnest("gameLeaders") %>% tidyr::unnest("homeLeaders", names_sep = '_') %>% tidyr::unnest("awayLeaders", names_sep = '_') %>% tidyr::unnest("pbOdds", names_sep = '_') colnames(games) <- gsub("homeTeam","home", colnames(games)) colnames(games) <- gsub("awayTeam","away", colnames(games)) games <- games %>% janitor::clean_names() %>% make_wehoop_data("WNBA Today's Scoreboard Information from NBA.com", Sys.time()) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no today's scoreboard data for {game_date} available!")) }, warning = function(w) { }, finally = { } ) return(games) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_scoreboard.R
#' **Get WNBA Stats API Shot Chart Detail** #' @name wnba_shotchartdetail NULL #' @title #' **Get WNBA Stats API Shot Chart Detail** #' @rdname wnba_shotchartdetail #' @author Saiem Gilani #' @param context_measure context_measure #' @param date_from date_from #' @param date_to date_to #' @param game_id game_id #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param period period #' @param player_id player_id #' @param player_position player_position #' @param rookie_year rookie_year #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: LeagueAverages, Shot_Chart_Detail #' #' **Shot_Chart_Detail** #' #' #' |col_name |types | #' |:-------------------|:---------| #' |GRID_TYPE |character | #' |GAME_ID |character | #' |GAME_EVENT_ID |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |PERIOD |character | #' |MINUTES_REMAINING |character | #' |SECONDS_REMAINING |character | #' |EVENT_TYPE |character | #' |ACTION_TYPE |character | #' |SHOT_TYPE |character | #' |SHOT_ZONE_BASIC |character | #' |SHOT_ZONE_AREA |character | #' |SHOT_ZONE_RANGE |character | #' |SHOT_DISTANCE |character | #' |LOC_X |character | #' |LOC_Y |character | #' |SHOT_ATTEMPTED_FLAG |character | #' |SHOT_MADE_FLAG |character | #' |GAME_DATE |character | #' |HTM |character | #' |VTM |character | #' #' **LeagueAverages** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GRID_TYPE |character | #' |SHOT_ZONE_BASIC |character | #' |SHOT_ZONE_AREA |character | #' |SHOT_ZONE_RANGE |character | #' |FGA |character | #' |FGM |character | #' |FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Shooting Functions #' @details #' ```r #' wnba_shotchartdetail(league_id = '10', player_id = '1628932', season = most_recent_wnba_season() - 1) #' ``` wnba_shotchartdetail <- function( context_measure = 'FGA', date_from = '', date_to = '', game_id = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', period = 0, player_id = '1628932', player_position = '', rookie_year = '', season = most_recent_wnba_season() - 1, season_segment = '', season_type = 'Regular Season', team_id = 0, vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "shotchartdetail" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( ContextMeasure = context_measure, DateFrom = date_from, DateTo = date_to, GameID = game_id, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, Period = period, PlayerID = player_id, PlayerPosition = player_position, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no shot chart detail data for {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Shot Chart League-Wide** #' @name wnba_shotchartleaguewide NULL #' @title #' **Get WNBA Stats API Shot Chart League-Wide** #' @rdname wnba_shotchartleaguewide #' @author Saiem Gilani #' @param league_id League - default: '10'. Other options include '00': NBA, '20': G-League #' @param season season #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: League_Wide #' #' **League_Wide** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GRID_TYPE |character | #' |SHOT_ZONE_BASIC |character | #' |SHOT_ZONE_AREA |character | #' |SHOT_ZONE_RANGE |character | #' |FGA |character | #' |FGM |character | #' |FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Shooting Functions #' @family WNBA League Functions #' @details #' ```r #' wnba_shotchartleaguewide(league_id = '10', season = most_recent_wnba_season() - 1) #' ``` wnba_shotchartleaguewide <- function( league_id = '10', season = most_recent_wnba_season() - 1, ...){ version <- "shotchartleaguewide" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league-wide shot chart data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Shot Chart for Lineups** #' @name wnba_shotchartlineupdetail NULL #' @title #' **Get WNBA Stats API Shot Chart for Lineups** #' @rdname wnba_shotchartlineupdetail #' @author Saiem Gilani #' @param ahead_behind ahead_behind #' @param cfid cfid #' @param cfparams cfparams #' @param clutch_time clutch_time #' @param conference conference #' @param context_filter context_filter #' @param context_measure context_measure #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param end_period end_period #' @param end_range end_range #' @param group_id group_id #' @param game_event_id game_event_id #' @param game_id game_id #' @param game_segment game_segment #' @param group_mode group_mode #' @param group_quantity group_quantity #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param on_off on_off #' @param opp_player_id opp_player_id #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param period period #' @param player_id player_id #' @param player_id1 player_id1 #' @param player_id2 player_id2 #' @param player_id3 player_id3 #' @param player_id4 player_id4 #' @param player_id5 player_id5 #' @param player_position player_position #' @param point_diff point_diff #' @param position position #' @param range_type range_type #' @param rookie_year rookie_year #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param start_period start_period #' @param start_range start_range #' @param starter_bench starter_bench #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_player_id1 vs_player_id1 #' @param vs_player_id2 vs_player_id2 #' @param vs_player_id3 vs_player_id3 #' @param vs_player_id4 vs_player_id4 #' @param vs_player_id5 vs_player_id5 #' @param vs_team_id vs_team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ShotChartLineupDetail, ShotChartLineupLeagueAverage #' #' **ShotChartLineupDetail** #' #' #' |col_name |types | #' |:-------------------|:---------| #' |GRID_TYPE |character | #' |GAME_ID |character | #' |GAME_EVENT_ID |character | #' |GROUP_ID |character | #' |GROUP_NAME |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |PERIOD |character | #' |MINUTES_REMAINING |character | #' |SECONDS_REMAINING |character | #' |EVENT_TYPE |character | #' |ACTION_TYPE |character | #' |SHOT_TYPE |character | #' |SHOT_ZONE_BASIC |character | #' |SHOT_ZONE_AREA |character | #' |SHOT_ZONE_RANGE |character | #' |SHOT_DISTANCE |character | #' |LOC_X |character | #' |LOC_Y |character | #' |SHOT_ATTEMPTED_FLAG |character | #' |SHOT_MADE_FLAG |character | #' |GAME_DATE |character | #' |HTM |character | #' |VTM |character | #' #' **ShotChartLineupLeagueAverage** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GRID_TYPE |character | #' |SHOT_ZONE_BASIC |character | #' |SHOT_ZONE_AREA |character | #' |SHOT_ZONE_RANGE |character | #' |FGA |character | #' |FGM |character | #' |FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Shooting Functions #' @family WNBA Lineup Functions #' @details #' ```r #' wnba_shotchartlineupdetail(group_id = '-100720-202250-204319-1627668-1628931-', season = most_recent_wnba_season()) #' ``` wnba_shotchartlineupdetail <- function( ahead_behind = '', cfid = '', cfparams = '', clutch_time = '', conference = '', context_filter = '', context_measure = 'FGA', date_from = '', date_to = '', division = '', end_period = '10', end_range = '28800', group_id = '-100720-202250-204319-1627668-1628931-', game_event_id = '', game_id = '', game_segment = '', group_mode = '', group_quantity = '5', last_n_games = '0', league_id = '10', location = '', month = '0', on_off = '', opp_player_id = '', opponent_team_id = '0', outcome = '', po_round = '0', period = '0', player_id = '0', player_id1 = '', player_id2 = '', player_id3 = '', player_id4 = '', player_id5 = '', player_position = '', point_diff = '', position = '', range_type = '0', rookie_year = '', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', start_period = '1', start_range = '0', starter_bench = '', team_id = '1611661328', vs_conference = '', vs_division = '', vs_player_id1 = '', vs_player_id2 = '', vs_player_id3 = '', vs_player_id4 = '', vs_player_id5 = '', vs_team_id = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "shotchartlineupdetail" endpoint <- wnba_endpoint(version) full_url <- endpoint group_id2 <- group_id params <- list( AheadBehind = ahead_behind, CFID = cfid, CFPARAMS = cfparams, ClutchTime = clutch_time, Conference = conference, ContextFilter = context_filter, ContextMeasure = context_measure, DateFrom = date_from, DateTo = date_to, Division = division, EndPeriod = end_period, EndRange = end_range, GROUP_ID = group_id, GameEventID = game_event_id, GameID = game_id, GameSegment = game_segment, GroupID = group_id2, GroupMode = group_mode, GroupQuantity = group_quantity, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OnOff = on_off, OppPlayerID = opp_player_id, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, Period = period, PlayerID = player_id, PlayerID1 = player_id1, PlayerID2 = player_id2, PlayerID3 = player_id3, PlayerID4 = player_id4, PlayerID5 = player_id5, PlayerPosition = player_position, PointDiff = point_diff, Position = position, RangeType = range_type, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, StartPeriod = start_period, StartRange = start_range, StarterBench = starter_bench, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsPlayerID1 = vs_player_id1, VsPlayerID2 = vs_player_id2, VsPlayerID3 = vs_player_id3, VsPlayerID4 = vs_player_id4, VsPlayerID5 = vs_player_id5, VsTeamID = vs_team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no shot chart lineup data available for {season}! (group_id: {group_id})")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_shotchart.R
#' **Get WNBA Stats API Teams** #' @name wnba_teams NULL #' @title #' **Get WNBA Stats API Teams** #' @rdname wnba_teams #' @author Saiem Gilani #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a data frame with the following columns: #' #' |col_name |types | #' |:-----------------|:---------| #' |league_id |character | #' |season_id |character | #' |team_id |character | #' |team_city |character | #' |team_name |character | #' |team_slug |character | #' |conference |character | #' |division |character | #' |team_abbreviation |character | #' |team_name_full |character | #' |season |character | #' |espn_team_id |integer | #' |team |character | #' |mascot |character | #' |display_name |character | #' |abbreviation |character | #' |color |character | #' |alternate_color |character | #' |logo |character | #' |logo_dark |character | #' |wnba_logo_svg |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teams() #' ``` wnba_teams <- function(...){ tryCatch( expr = { standings <- wnba_leaguestandingsv3(season = most_recent_wnba_season(), ...) %>% purrr::pluck("Standings") league_gamelog <- wnba_leaguegamelog(league_id = '10', season = most_recent_wnba_season(), ...) %>% purrr::pluck("LeagueGameLog") %>% dplyr::rename("team_name_full" = "TEAM_NAME") %>% dplyr::select( "TEAM_ID", "TEAM_ABBREVIATION", "team_name_full") %>% dplyr::distinct() standings <- standings %>% dplyr::left_join(league_gamelog, by = c("TeamID" = "TEAM_ID")) wnba_teams <- standings %>% dplyr::select(dplyr::any_of(c( "LeagueID", "SeasonID", "TeamID", "TeamCity", "TeamName", "TeamSlug", "Conference", "Division", "TEAM_ABBREVIATION", "team_name_full"))) %>% dplyr::mutate( Season = paste0('', most_recent_wnba_season())) %>% dplyr::arrange(.data$team_name_full) espn_wnba_teams <- espn_wnba_teams() %>% dplyr::rename("espn_team_id" = "team_id") wnba_teams <- wnba_teams %>% dplyr::left_join(espn_wnba_teams, by = c("TeamName" = "short_name")) wnba_teams <- wnba_teams %>% dplyr::mutate( espn_team_id = as.integer(.data$espn_team_id), wnba_logo_svg = paste0("https://stats.wnba.com/media/img/teams/logos/", .data$TEAM_ABBREVIATION, ".svg")) %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team details data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(wnba_teams) } #' **Get WNBA Stats API Team Details** #' @name wnba_teamdetails NULL #' @title #' **Get WNBA Stats API Team Details** #' @rdname wnba_teamdetails #' @author Saiem Gilani #' @param team_id Team ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamAwardsChampionships, #' TeamAwardsConf, TeamAwardsDiv, TeamBackground, #' TeamHistory, TeamHof, TeamRetired, TeamSocialSites #' #' **TeamBackground** #' #' #' |col_name |types | #' |:------------------|:---------| #' |TEAM_ID |character | #' |ABBREVIATION |character | #' |NICKNAME |character | #' |YEARFOUNDED |character | #' |CITY |character | #' |ARENA |character | #' |ARENACAPACITY |character | #' |OWNER |character | #' |GENERALMANAGER |character | #' |HEADCOACH |character | #' |DLEAGUEAFFILIATION |character | #' #' **TeamHistory** #' #' #' |col_name |types | #' |:--------------|:---------| #' |TEAM_ID |character | #' |CITY |character | #' |NICKNAME |character | #' |YEARFOUNDED |character | #' |YEARACTIVETILL |character | #' #' **TeamSocialSites** #' #' #' |col_name |types | #' |:------------|:---------| #' |ACCOUNTTYPE |character | #' |WEBSITE_LINK |character | #' #' **TeamAwardsChampionships** #' #' #' |col_name |types | #' |:------------|:---------| #' |YEARAWARDED |character | #' |OPPOSITETEAM |character | #' #' **TeamAwardsConf** #' #' #' |col_name |types | #' |:------------|:-------| #' |YEARAWARDED |integer | #' |OPPOSITETEAM |integer | #' #' **TeamAwardsDiv** #' #' #' |col_name |types | #' |:------------|:-------| #' |YEARAWARDED |integer | #' |OPPOSITETEAM |integer | #' #' **TeamHof** #' #' #' |col_name |types | #' |:---------------|:---------| #' |PLAYERID |character | #' |PLAYER |character | #' |POSITION |character | #' |JERSEY |character | #' |SEASONSWITHTEAM |character | #' |YEAR |character | #' #' **TeamRetired** #' #' #' |col_name |types | #' |:---------------|:---------| #' |PLAYERID |character | #' |PLAYER |character | #' |POSITION |character | #' |JERSEY |character | #' |SEASONSWITHTEAM |character | #' |YEAR |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdetails(team_id = '1611661328') #' ``` wnba_teamdetails <- function( team_id = '1611661328', ...){ version <- "teamdetails" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team details data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Estimated Metrics** #' @name wnba_teamestimatedmetrics NULL #' @title #' **Get WNBA Stats API Team Estimated Metrics** #' @rdname wnba_teamestimatedmetrics #' @author Saiem Gilani #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamEstimatedMetrics #' #' **TeamEstimatedMetrics** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_NAME |character | #' |TEAM_ID |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |E_OFF_RATING |character | #' |E_DEF_RATING |character | #' |E_NET_RATING |character | #' |E_PACE |character | #' |E_AST_RATIO |character | #' |E_OREB_PCT |character | #' |E_DREB_PCT |character | #' |E_REB_PCT |character | #' |E_TM_TOV_PCT |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |E_OFF_RATING_RANK |character | #' |E_DEF_RATING_RANK |character | #' |E_NET_RATING_RANK |character | #' |E_AST_RATIO_RANK |character | #' |E_OREB_PCT_RANK |character | #' |E_DREB_PCT_RANK |character | #' |E_REB_PCT_RANK |character | #' |E_TM_TOV_PCT_RANK |character | #' |E_PACE_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamestimatedmetrics() #' ``` wnba_teamestimatedmetrics <- function( league_id = '10', season = most_recent_wnba_season(), season_type = 'Regular Season', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamestimatedmetrics" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, SeasonType = season_type ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- purrr::map(1:length(resp$resultSet$name), function(x){ data <- resp$resultSet$rowSet %>% data.frame(stringsAsFactors = FALSE) %>% dplyr::as_tibble() json_names <- resp$resultSet$headers colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSet$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team estimated metrics data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Game Log** #' @name wnba_teamgamelog NULL #' @title #' **Get WNBA Stats API Team Game Log** #' @rdname wnba_teamgamelog #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param team_id Team ID #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamGameLog #' #' **TeamGameLog** #' #' #' |col_name |types | #' |:---------|:---------| #' |Team_ID |character | #' |Game_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |STL |character | #' |BLK |character | #' |TOV |character | #' |PF |character | #' |PTS |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamgamelog(team_id = '1611661328') #' ``` wnba_teamgamelog <- function( date_from = '', date_to = '', league_id = '10', season = most_recent_wnba_season(), season_type = 'Regular Season', team_id = '1611661328', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamgamelog" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, LeagueID = league_id, Season = season, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team game log data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Game Logs** #' @name wnba_teamgamelogs NULL #' @title #' **Get WNBA Stats API Team Game Logs** #' @rdname wnba_teamgamelogs #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param per_mode per_mode #' @param period period #' @param player_id Player ID #' @param season Season - format 2020-21 #' @param season_segment season_segment #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamGameLogs #' #' **TeamGameLogs** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |SEASON_YEAR |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GAME_ID |character | #' |GAME_DATE |character | #' |MATCHUP |character | #' |WL |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' [Teams Game Log](https://www.nba.com/stats/team/1611661328/boxscores) #' ```r #' wnba_teamgamelogs(team_id = '1611661328') #' ``` wnba_teamgamelogs <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', per_mode = 'Totals', period = 0, player_id = '', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamgamelogs" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PerMode = per_mode, Period = period, PlayerID = player_id, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team game logs for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Historical Leaders** #' @name wnba_teamhistoricalleaders NULL #' @title #' **Get WNBA Stats API Team Historical Leaders** #' @rdname wnba_teamhistoricalleaders #' @author Saiem Gilani #' @param league_id league_id #' @param season_id season_id #' @param team_id team_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: CareerLeadersByTeam #' #' **CareerLeadersByTeam** #' #' #' |col_name |types | #' |:-------------|:---------| #' |TEAM_ID |character | #' |PTS |character | #' |PTS_PERSON_ID |character | #' |PTS_PLAYER |character | #' |AST |character | #' |AST_PERSON_ID |character | #' |AST_PLAYER |character | #' |REB |character | #' |REB_PERSON_ID |character | #' |REB_PLAYER |character | #' |BLK |character | #' |BLK_PERSON_ID |character | #' |BLK_PLAYER |character | #' |STL |character | #' |STL_PERSON_ID |character | #' |STL_PLAYER |character | #' |SEASON_YEAR |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamhistoricalleaders(team_id = '1611661328') #' ``` wnba_teamhistoricalleaders <- function( league_id = '10', season_id = '22022', team_id = '1611661328', ...){ version <- "teamhistoricalleaders" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, SeasonID = season_id, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team historical leaders data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Common Info** #' @name wnba_teaminfocommon NULL #' @title #' **Get WNBA Stats API Team Common Info** #' @rdname wnba_teaminfocommon #' @author Saiem Gilani #' @param league_id League - default: '10'. Other options include '00': NBA, '20': G-League #' @param team_id Team ID #' @param season Season - format 2020-21 #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: AvailableSeasons, TeamInfoCommon, #' TeamSeasonRanks #' #' **TeamInfoCommon** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |TEAM_ID |character | #' |SEASON_YEAR |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_CONFERENCE |character | #' |TEAM_DIVISION |character | #' |TEAM_CODE |character | #' |TEAM_SLUG |character | #' |W |character | #' |L |character | #' |PCT |character | #' |CONF_RANK |character | #' |DIV_RANK |character | #' |MIN_YEAR |character | #' |MAX_YEAR |character | #' #' **TeamSeasonRanks** #' #' #' |col_name |types | #' |:------------|:---------| #' |LEAGUE_ID |character | #' |SEASON_ID |character | #' |TEAM_ID |character | #' |PTS_RANK |character | #' |PTS_PG |character | #' |REB_RANK |character | #' |REB_PG |character | #' |AST_RANK |character | #' |AST_PG |character | #' |OPP_PTS_RANK |character | #' |OPP_PTS_PG |character | #' #' **AvailableSeasons** #' #' #' |col_name |types | #' |:---------|:---------| #' |SEASON_ID |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teaminfocommon(team_id = '1611661328') #' ``` wnba_teaminfocommon <- function( league_id = '10', season = most_recent_wnba_season(), season_type = 'Regular Season', team_id = '1611661328', ...){ # Intentionally not commented out season_type <- gsub(' ', '+', season_type) version <- "teaminfocommon" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, Season = season, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team common info data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Player On/Off Details** #' @name wnba_teamplayeronoffdetails NULL #' @title #' **Get WNBA Stats API Team Player On/Off Details** #' @rdname wnba_teamplayeronoffdetails #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OverallTeamPlayerOnOffDetails, #' PlayersOffCourtTeamPlayerOnOffDetails, PlayersOnCourtTeamPlayerOnOffDetails #' #' **OverallTeamPlayerOnOffDetails** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PlayersOnCourtTeamPlayerOnOffDetails** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PlayersOffCourtTeamPlayerOnOffDetails** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamplayeronoffdetails(team_id = '1611661328') #' ``` wnba_teamplayeronoffdetails <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamplayeronoffdetails" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team player on off details data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Player On/Off Summary** #' @name wnba_teamplayeronoffsummary NULL #' @title #' **Get WNBA Stats API Team Player On/Off Summary** #' @rdname wnba_teamplayeronoffsummary #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OverallTeamPlayerOnOffSummary, #' PlayersOffCourtTeamPlayerOnOffSummary, PlayersOnCourtTeamPlayerOnOffSummary #' #' **OverallTeamPlayerOnOffSummary** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PlayersOnCourtTeamPlayerOnOffSummary** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |MIN |character | #' |PLUS_MINUS |character | #' |OFF_RATING |character | #' |DEF_RATING |character | #' |NET_RATING |character | #' #' **PlayersOffCourtTeamPlayerOnOffSummary** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |MIN |character | #' |PLUS_MINUS |character | #' |OFF_RATING |character | #' |DEF_RATING |character | #' |NET_RATING |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamplayeronoffsummary(team_id = '1611661328') #' ``` wnba_teamplayeronoffsummary <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamplayeronoffsummary" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team player on off summary data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Player Dashboard** #' @name wnba_teamplayerdashboard NULL #' @title #' **Get WNBA Stats API Team Player Dashboard** #' @rdname wnba_teamplayerdashboard #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: PlayersSeasonTotals, TeamOverall #' #' **TeamOverall** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_NAME |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PlayersSeasonTotals** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |NICKNAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamplayerdashboard(team_id = '1611661328') #' ``` wnba_teamplayerdashboard <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamplayerdashboard" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team player dashboard data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Year by Year Stats** #' @name wnba_teamyearbyyearstats NULL #' @title #' **Get WNBA Stats API Team Year by Year Stats** #' @rdname wnba_teamyearbyyearstats #' @author Saiem Gilani #' @param league_id League - default: '00'. Other options include '10': WNBA, '20': G-League #' @param per_mode Per Mode #' @param team_id Team ID #' @param season_type Season Type - Regular Season, Playoffs, All-Star #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamStats #' #' **TeamStats** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |TEAM_ID |character | #' |TEAM_CITY |character | #' |TEAM_NAME |character | #' |YEAR |character | #' |GP |character | #' |WINS |character | #' |LOSSES |character | #' |WIN_PCT |character | #' |CONF_RANK |character | #' |DIV_RANK |character | #' |PO_WINS |character | #' |PO_LOSSES |character | #' |CONF_COUNT |character | #' |DIV_COUNT |character | #' |NBA_FINALS_APPEARANCE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |PF |character | #' |STL |character | #' |TOV |character | #' |BLK |character | #' |PTS |character | #' |PTS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamyearbyyearstats(team_id = '1611661328') #' ``` wnba_teamyearbyyearstats <- function( league_id = '10', per_mode = 'Totals', season_type = 'Regular Season', team_id = '1611661328', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamyearbyyearstats" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( LeagueID = league_id, PerMode = per_mode, SeasonType = season_type, TeamID = team_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team year-by-year stats data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team vs Player** #' @name wnba_teamvsplayer NULL #' @title #' **Get WNBA Stats API Team vs Player** #' @rdname wnba_teamvsplayer #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param player_id Player ID #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_player_id vs_player_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OnOffCourt, Overall, ShotAreaOffCourt, #' ShotAreaOnCourt, ShotAreaOverall, ShotDistanceOffCourt, ShotDistanceOnCourt, #' ShotDistanceOverall, vsPlayerOverall #' #' **Overall** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **vsPlayerOverall** #' #' #' |col_name |types | #' |:---------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |PLAYER_ID |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |NBA_FANTASY_PTS |character | #' |DD2 |character | #' |TD3 |character | #' |WNBA_FANTASY_PTS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' |NBA_FANTASY_PTS_RANK |character | #' |DD2_RANK |character | #' |TD3_RANK |character | #' |WNBA_FANTASY_PTS_RANK |character | #' #' **OnOffCourt** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ShotDistanceOverall** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotDistanceOnCourt** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotDistanceOffCourt** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOverall** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOnCourt** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' **ShotAreaOffCourt** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |VS_PLAYER_ID |character | #' |VS_PLAYER_NAME |character | #' |COURT_STATUS |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamvsplayer(team_id = '1611661328', vs_player_id = '1628932') #' ``` wnba_teamvsplayer <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', po_round = '', pace_adjust = 'N', per_mode = 'Totals', period = 0, player_id = '', plus_minus = 'N', rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', vs_player_id = '1628932', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamvsplayer" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PORound = po_round, PaceAdjust = pace_adjust, PerMode = per_mode, Period = period, PlayerID = player_id, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsPlayerID = vs_player_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team vs player data for {team_id} and {player_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Game Streak Finder** #' @name wnba_teamgamestreakfinder NULL #' @title #' **Get WNBA Stats API Team Game Streak Finder** #' @rdname wnba_teamgamestreakfinder #' @author Saiem Gilani #' @param active_streaks_only active_streaks_only #' @param active_teams_only active_teams_only #' @param btr_opp_ast btr_opp_ast #' @param btr_opp_blk btr_opp_blk #' @param btr_opp_dreb btr_opp_dreb #' @param btr_opp_fg3a btr_opp_fg3a #' @param btr_opp_fg3m btr_opp_fg3m #' @param btr_opp_fg3_pct btr_opp_fg3_pct #' @param btr_opp_fga btr_opp_fga #' @param btr_opp_fgm btr_opp_fgm #' @param btr_opp_fg_pct btr_opp_fg_pct #' @param btr_opp_fta btr_opp_fta #' @param btr_opp_ftm btr_opp_ftm #' @param btr_opp_ft_pct btr_opp_ft_pct #' @param btr_opp_oreb btr_opp_oreb #' @param btr_opp_pf btr_opp_pf #' @param btr_opp_pts btr_opp_pts #' @param btr_opp_pts2nd_chance btr_opp_pts2nd_chance #' @param btr_opp_pts_fb btr_opp_pts_fb #' @param btr_opp_pts_off_tov btr_opp_pts_off_tov #' @param btr_opp_pts_paint btr_opp_pts_paint #' @param btr_opp_reb btr_opp_reb #' @param btr_opp_stl btr_opp_stl #' @param btr_opp_tov btr_opp_tov #' @param conference conference #' @param date_from date_from #' @param date_to date_to #' @param division division #' @param et_ast et_ast #' @param et_blk et_blk #' @param et_dd et_dd #' @param et_dreb et_dreb #' @param et_fg3a et_fg3a #' @param et_fg3m et_fg3m #' @param et_fg3_pct et_fg3_pct #' @param et_fga et_fga #' @param et_fgm et_fgm #' @param et_fg_pct et_fg_pct #' @param et_fta et_fta #' @param et_ftm et_ftm #' @param et_ft_pct et_ft_pct #' @param et_minutes et_minutes #' @param eq_opp_pts2nd_chance eq_opp_pts2nd_chance #' @param eq_opp_pts_fb eq_opp_pts_fb #' @param eq_opp_pts_off_tov eq_opp_pts_off_tov #' @param eq_opp_pts_paint eq_opp_pts_paint #' @param et_oreb et_oreb #' @param et_pf et_pf #' @param et_pts et_pts #' @param eq_pts2nd_chance eq_pts2nd_chance #' @param eq_pts_fb eq_pts_fb #' @param eq_pts_off_tov eq_pts_off_tov #' @param eq_pts_paint eq_pts_paint #' @param et_reb et_reb #' @param et_stl et_stl #' @param et_td et_td #' @param et_tov et_tov #' @param game_id game_id #' @param gt_ast gt_ast #' @param gt_blk gt_blk #' @param gt_dd gt_dd #' @param gt_dreb gt_dreb #' @param gt_fg3a gt_fg3a #' @param gt_fg3m gt_fg3m #' @param gt_fg3_pct gt_fg3_pct #' @param gt_fga gt_fga #' @param gt_fgm gt_fgm #' @param gt_fg_pct gt_fg_pct #' @param gt_fta gt_fta #' @param gt_ftm gt_ftm #' @param gt_ft_pct gt_ft_pct #' @param gt_minutes gt_minutes #' @param gt_opp_ast gt_opp_ast #' @param gt_opp_blk gt_opp_blk #' @param gt_opp_dreb gt_opp_dreb #' @param gt_opp_fg3a gt_opp_fg3a #' @param gt_opp_fg3m gt_opp_fg3m #' @param gt_opp_fg3_pct gt_opp_fg3_pct #' @param gt_opp_fga gt_opp_fga #' @param gt_opp_fgm gt_opp_fgm #' @param gt_opp_fg_pct gt_opp_fg_pct #' @param gt_opp_fta gt_opp_fta #' @param gt_opp_ftm gt_opp_ftm #' @param gt_opp_ft_pct gt_opp_ft_pct #' @param gt_opp_oreb gt_opp_oreb #' @param gt_opp_pf gt_opp_pf #' @param gt_opp_pts gt_opp_pts #' @param gt_opp_pts2nd_chance gt_opp_pts2nd_chance #' @param gt_opp_pts_fb gt_opp_pts_fb #' @param gt_opp_pts_off_tov gt_opp_pts_off_tov #' @param gt_opp_pts_paint gt_opp_pts_paint #' @param gt_opp_reb gt_opp_reb #' @param gt_opp_stl gt_opp_stl #' @param gt_opp_tov gt_opp_tov #' @param gt_oreb gt_oreb #' @param gt_pf gt_pf #' @param gt_pts gt_pts #' @param gt_pts2nd_chance gt_pts2nd_chance #' @param gt_pts_fb gt_pts_fb #' @param gt_pts_off_tov gt_pts_off_tov #' @param gt_pts_paint gt_pts_paint #' @param gt_reb gt_reb #' @param gt_stl gt_stl #' @param gt_td gt_td #' @param gt_tov gt_tov #' @param lstreak lstreak #' @param league_id league_id #' @param location location #' @param lt_ast lt_ast #' @param lt_blk lt_blk #' @param lt_dd lt_dd #' @param lt_dreb lt_dreb #' @param lt_fg3a lt_fg3a #' @param lt_fg3m lt_fg3m #' @param lt_fg3_pct lt_fg3_pct #' @param lt_fga lt_fga #' @param lt_fgm lt_fgm #' @param lt_fg_pct lt_fg_pct #' @param lt_fta lt_fta #' @param lt_ftm lt_ftm #' @param lt_ft_pct lt_ft_pct #' @param lt_minutes lt_minutes #' @param lt_opp_ast lt_opp_ast #' @param lt_opp_blk lt_opp_blk #' @param lt_opp_dreb lt_opp_dreb #' @param lt_opp_fg3a lt_opp_fg3a #' @param lt_opp_fg3m lt_opp_fg3m #' @param lt_opp_fg3_pct lt_opp_fg3_pct #' @param lt_opp_fga lt_opp_fga #' @param lt_opp_fgm lt_opp_fgm #' @param lt_opp_fg_pct lt_opp_fg_pct #' @param lt_opp_fta lt_opp_fta #' @param lt_opp_ftm lt_opp_ftm #' @param lt_opp_ft_pct lt_opp_ft_pct #' @param lt_opp_oreb lt_opp_oreb #' @param lt_opp_pf lt_opp_pf #' @param lt_opp_pts lt_opp_pts #' @param lt_opp_pts2nd_chance lt_opp_pts2nd_chance #' @param lt_opp_pts_fb lt_opp_pts_fb #' @param lt_opp_pts_off_tov lt_opp_pts_off_tov #' @param lt_opp_pts_paint lt_opp_pts_paint #' @param lt_opp_reb lt_opp_reb #' @param lt_opp_stl lt_opp_stl #' @param lt_opp_tov lt_opp_tov #' @param lt_oreb lt_oreb #' @param lt_pf lt_pf #' @param lt_pts lt_pts #' @param lt_pts2nd_chance lt_pts2nd_chance #' @param lt_pts_fb lt_pts_fb #' @param lt_pts_off_tov lt_pts_off_tov #' @param lt_pts_paint lt_pts_paint #' @param lt_reb lt_reb #' @param lt_stl lt_stl #' @param lt_td lt_td #' @param lt_tov lt_tov #' @param min_games min_games #' @param outcome outcome #' @param po_round po_round #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param vs_team_id vs_team_id #' @param wstreak wstreak #' @param wrs_opp_ast wrs_opp_ast #' @param wrs_opp_blk wrs_opp_blk #' @param wrs_opp_dreb wrs_opp_dreb #' @param wrs_opp_fg3a wrs_opp_fg3a #' @param wrs_opp_fg3m wrs_opp_fg3m #' @param wrs_opp_fg3_pct wrs_opp_fg3_pct #' @param wrs_opp_fga wrs_opp_fga #' @param wrs_opp_fgm wrs_opp_fgm #' @param wrs_opp_fg_pct wrs_opp_fg_pct #' @param wrs_opp_fta wrs_opp_fta #' @param wrs_opp_ftm wrs_opp_ftm #' @param wrs_opp_ft_pct wrs_opp_ft_pct #' @param wrs_opp_oreb wrs_opp_oreb #' @param wrs_opp_pf wrs_opp_pf #' @param wrs_opp_pts wrs_opp_pts #' @param wrs_opp_pts2nd_chance wrs_opp_pts2nd_chance #' @param wrs_opp_pts_fb wrs_opp_pts_fb #' @param wrs_opp_pts_off_tov wrs_opp_pts_off_tov #' @param wrs_opp_pts_paint wrs_opp_pts_paint #' @param wrs_opp_reb wrs_opp_reb #' @param wrs_opp_stl wrs_opp_stl #' @param wrs_opp_tov wrs_opp_tov #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: TeamGameStreakFinderParametersResults #' #' **TeamGameStreakFinderParametersResults** #' #' #' |col_name |types | #' |:------------|:---------| #' |TEAM_NAME |character | #' |TEAM_ID |character | #' |GAMESTREAK |character | #' |STARTDATE |character | #' |ENDDATE |character | #' |ACTIVESTREAK |character | #' |NUMSEASONS |character | #' |LASTSEASON |character | #' |FIRSTSEASON |character | #' |ABBREVIATION |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @family WNBA Game Finder Functions #' @details #' ```r #' wnba_teamgamestreakfinder() #' ``` wnba_teamgamestreakfinder <- function( active_streaks_only = '', active_teams_only = '', btr_opp_ast = '', btr_opp_blk = '', btr_opp_dreb = '', btr_opp_fg3a = '', btr_opp_fg3m = '', btr_opp_fg3_pct = '', btr_opp_fga = '', btr_opp_fgm = '', btr_opp_fg_pct = '', btr_opp_fta = '', btr_opp_ftm = '', btr_opp_ft_pct = '', btr_opp_oreb = '', btr_opp_pf = '', btr_opp_pts = '', btr_opp_pts2nd_chance = '', btr_opp_pts_fb = '', btr_opp_pts_off_tov = '', btr_opp_pts_paint = '', btr_opp_reb = '', btr_opp_stl = '', btr_opp_tov = '', conference = '', date_from = '', date_to = '', division = '', et_ast = '', et_blk = '', et_dd = '', et_dreb = '', et_fg3a = '', et_fg3m = '', et_fg3_pct = '', et_fga = '', et_fgm = '', et_fg_pct = '', et_fta = '', et_ftm = '', et_ft_pct = '', et_minutes = '', eq_opp_pts2nd_chance = '', eq_opp_pts_fb = '', eq_opp_pts_off_tov = '', eq_opp_pts_paint = '', et_oreb = '', et_pf = '', et_pts = '', eq_pts2nd_chance = '', eq_pts_fb = '', eq_pts_off_tov = '', eq_pts_paint = '', et_reb = '', et_stl = '', et_td = '', et_tov = '', game_id = '', gt_ast = '', gt_blk = '', gt_dd = '', gt_dreb = '', gt_fg3a = '', gt_fg3m = '', gt_fg3_pct = '', gt_fga = '', gt_fgm = '', gt_fg_pct = '', gt_fta = '', gt_ftm = '', gt_ft_pct = '', gt_minutes = '', gt_opp_ast = '', gt_opp_blk = '', gt_opp_dreb = '', gt_opp_fg3a = '', gt_opp_fg3m = '', gt_opp_fg3_pct = '', gt_opp_fga = '', gt_opp_fgm = '', gt_opp_fg_pct = '', gt_opp_fta = '', gt_opp_ftm = '', gt_opp_ft_pct = '', gt_opp_oreb = '', gt_opp_pf = '', gt_opp_pts = '', gt_opp_pts2nd_chance = '', gt_opp_pts_fb = '', gt_opp_pts_off_tov = '', gt_opp_pts_paint = '', gt_opp_reb = '', gt_opp_stl = '', gt_opp_tov = '', gt_oreb = '', gt_pf = '', gt_pts = '', gt_pts2nd_chance = '', gt_pts_fb = '', gt_pts_off_tov = '', gt_pts_paint = '', gt_reb = '', gt_stl = '', gt_td = '', gt_tov = '', lstreak = '', league_id = '10', location = '', lt_ast = '', lt_blk = '', lt_dd = '', lt_dreb = '', lt_fg3a = '', lt_fg3m = '', lt_fg3_pct = '', lt_fga = '', lt_fgm = '', lt_fg_pct = '', lt_fta = '', lt_ftm = '', lt_ft_pct = '', lt_minutes = '', lt_opp_ast = '', lt_opp_blk = '', lt_opp_dreb = '', lt_opp_fg3a = '', lt_opp_fg3m = '', lt_opp_fg3_pct = '', lt_opp_fga = '', lt_opp_fgm = '', lt_opp_fg_pct = '', lt_opp_fta = '', lt_opp_ftm = '', lt_opp_ft_pct = '', lt_opp_oreb = '', lt_opp_pf = '', lt_opp_pts = '', lt_opp_pts2nd_chance = '', lt_opp_pts_fb = '', lt_opp_pts_off_tov = '', lt_opp_pts_paint = '', lt_opp_reb = '', lt_opp_stl = '', lt_opp_tov = '', lt_oreb = '', lt_pf = '', lt_pts = '', lt_pts2nd_chance = '', lt_pts_fb = '', lt_pts_off_tov = '', lt_pts_paint = '', lt_reb = '', lt_stl = '', lt_td = '', lt_tov = '', min_games = '', outcome = '', po_round = '', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', team_id = '', vs_conference = '', vs_division = '', vs_team_id = '', wstreak = '', wrs_opp_ast = '', wrs_opp_blk = '', wrs_opp_dreb = '', wrs_opp_fg3a = '', wrs_opp_fg3m = '', wrs_opp_fg3_pct = '', wrs_opp_fga = '', wrs_opp_fgm = '', wrs_opp_fg_pct = '', wrs_opp_fta = '', wrs_opp_ftm = '', wrs_opp_ft_pct = '', wrs_opp_oreb = '', wrs_opp_pf = '', wrs_opp_pts = '', wrs_opp_pts2nd_chance = '', wrs_opp_pts_fb = '', wrs_opp_pts_off_tov = '', wrs_opp_pts_paint = '', wrs_opp_reb = '', wrs_opp_stl = '', wrs_opp_tov = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamgamestreakfinder" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( ActiveStreaksOnly = active_streaks_only, ActiveTeamsOnly = active_teams_only, BtrOPPAST = btr_opp_ast, BtrOPPBLK = btr_opp_blk, BtrOPPDREB = btr_opp_dreb, BtrOPPFG3A = btr_opp_fg3a, BtrOPPFG3M = btr_opp_fg3m, BtrOPPFG3PCT = btr_opp_fg3_pct, BtrOPPFGA = btr_opp_fga, BtrOPPFGM = btr_opp_fgm, BtrOPPFG_PCT = btr_opp_fg_pct, BtrOPPFTA = btr_opp_fta, BtrOPPFTM = btr_opp_ftm, BtrOPPFT_PCT = btr_opp_ft_pct, BtrOPPOREB = btr_opp_oreb, BtrOPPPF = btr_opp_pf, BtrOPPPTS = btr_opp_pts, BtrOPPPTS2NDCHANCE = btr_opp_pts2nd_chance, BtrOPPPTSFB = btr_opp_pts_fb, BtrOPPPTSOFFTOV = btr_opp_pts_off_tov, BtrOPPPTSPAINT = btr_opp_pts_paint, BtrOPPREB = btr_opp_reb, BtrOPPSTL = btr_opp_stl, BtrOPPTOV = btr_opp_tov, Conference = conference, DateFrom = date_from, DateTo = date_to, Division = division, EqAST = et_ast, EqBLK = et_blk, EqDD = et_dd, EqDREB = et_dreb, EqFG3A = et_fg3a, EqFG3M = et_fg3m, EqFG3_PCT = et_fg3_pct, EqFGA = et_fga, EqFGM = et_fgm, EqFG_PCT = et_fg_pct, EqFTA = et_fta, EqFTM = et_ftm, EqFT_PCT = et_ft_pct, EqMINUTES = et_minutes, EqOPPPTS2NDCHANCE = eq_opp_pts2nd_chance, EqOPPPTSFB = eq_opp_pts_fb, EqOPPPTSOFFTOV = eq_opp_pts_off_tov, EqOPPPTSPAINT = eq_opp_pts_paint, EqOREB = et_oreb, EqPF = et_pf, EqPTS = et_pts, EqPTS2NDCHANCE = eq_pts2nd_chance, EqPTSFB = eq_pts_fb, EqPTSOFFTOV = eq_pts_off_tov, EqPTSPAINT = eq_pts_paint, EqREB = et_reb, EqSTL = et_stl, EqTD = et_td, EqTOV = et_tov, GameID = game_id, GtAST = gt_ast, GtBLK = gt_blk, GtDD = gt_dd, GtDREB = gt_dreb, GtFG3A = gt_fg3a, GtFG3M = gt_fg3m, GtFG3_PCT = gt_fg3_pct, GtFGA = gt_fga, GtFGM = gt_fgm, GtFG_PCT = gt_fg_pct, GtFTA = gt_fta, GtFTM = gt_ftm, GtFT_PCT = gt_ft_pct, GtMINUTES = gt_minutes, GtOPPAST = gt_opp_ast, GtOPPBLK = gt_opp_blk, GtOPPDREB = gt_opp_dreb, GtOPPFG3A = gt_opp_fg3a, GtOPPFG3M = gt_opp_fg3m, GtOPPFG3PCT = gt_opp_fg3_pct, GtOPPFGA = gt_opp_fga, GtOPPFGM = gt_opp_fgm, GtOPPFG_PCT = gt_opp_fg_pct, GtOPPFTA = gt_opp_fta, GtOPPFTM = gt_opp_ftm, GtOPPFT_PCT = gt_opp_ft_pct, GtOPPOREB = gt_opp_oreb, GtOPPPF = gt_opp_pf, GtOPPPTS = gt_opp_pts, GtOPPPTS2NDCHANCE = gt_opp_pts2nd_chance, GtOPPPTSFB = gt_opp_pts_fb, GtOPPPTSOFFTOV = gt_opp_pts_off_tov, GtOPPPTSPAINT = gt_opp_pts_paint, GtOPPREB = gt_opp_reb, GtOPPSTL = gt_opp_stl, GtOPPTOV = gt_opp_tov, GtOREB = gt_oreb, GtPF = gt_pf, GtPTS = gt_pts, GtPTS2NDCHANCE = gt_pts2nd_chance, GtPTSFB = gt_pts_fb, GtPTSOFFTOV = gt_pts_off_tov, GtPTSPAINT = gt_pts_paint, GtREB = gt_reb, GtSTL = gt_stl, GtTD = gt_td, GtTOV = gt_tov, LeagueID = league_id, Location = location, LStreak = lstreak, LtAST = lt_ast, LtBLK = lt_blk, LtDD = lt_dd, LtDREB = lt_dreb, LtFG3A = lt_fg3a, LtFG3M = lt_fg3m, LtFG3_PCT = lt_fg3_pct, LtFGA = lt_fga, LtFGM = lt_fgm, LtFG_PCT = lt_fg_pct, LtFTA = lt_fta, LtFTM = lt_ftm, LtFT_PCT = lt_ft_pct, LtMINUTES = lt_minutes, LtOPPAST = lt_opp_ast, LtOPPBLK = lt_opp_blk, LtOPPDREB = lt_opp_dreb, LtOPPFG3A = lt_opp_fg3a, LtOPPFG3M = lt_opp_fg3m, LtOPPFG3PCT = lt_opp_fg3_pct, LtOPPFGA = lt_opp_fga, LtOPPFGM = lt_opp_fgm, LtOPPFG_PCT = lt_opp_fg_pct, LtOPPFTA = lt_opp_fta, LtOPPFTM = lt_opp_ftm, LtOPPFT_PCT = lt_opp_ft_pct, LtOPPOREB = lt_opp_oreb, LtOPPPF = lt_opp_pf, LtOPPPTS = lt_opp_pts, LtOPPPTS2NDCHANCE = lt_opp_pts2nd_chance, LtOPPPTSFB = lt_opp_pts_fb, LtOPPPTSOFFTOV = lt_opp_pts_off_tov, LtOPPPTSPAINT = lt_opp_pts_paint, LtOPPREB = lt_opp_reb, LtOPPSTL = lt_opp_stl, LtOPPTOV = lt_opp_tov, LtOREB = lt_oreb, LtPF = lt_pf, LtPTS = lt_pts, LtPTS2NDCHANCE = lt_pts2nd_chance, LtPTSFB = lt_pts_fb, LtPTSOFFTOV = lt_pts_off_tov, LtPTSPAINT = lt_pts_paint, LtREB = lt_reb, LtSTL = lt_stl, LtTD = lt_td, LtTOV = lt_tov, MinGames = min_games, Outcome = outcome, PORound = po_round, Season = season, SeasonSegment = season_segment, SeasonType = season_type, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division, VsTeamID = vs_team_id, WStreak = wstreak, WrsOPPAST = wrs_opp_ast, WrsOPPBLK = wrs_opp_blk, WrsOPPDREB = wrs_opp_dreb, WrsOPPFG3A = wrs_opp_fg3a, WrsOPPFG3M = wrs_opp_fg3m, WrsOPPFG3PCT = wrs_opp_fg3_pct, WrsOPPFGA = wrs_opp_fga, WrsOPPFGM = wrs_opp_fgm, WrsOPPFG_PCT = wrs_opp_fg_pct, WrsOPPFTA = wrs_opp_fta, WrsOPPFTM = wrs_opp_ftm, WrsOPPFT_PCT = wrs_opp_ft_pct, WrsOPPOREB = wrs_opp_oreb, WrsOPPPF = wrs_opp_pf, WrsOPPPTS = wrs_opp_pts, WrsOPPPTS2NDCHANCE = wrs_opp_pts2nd_chance, WrsOPPPTSFB = wrs_opp_pts_fb, WrsOPPPTSOFFTOV = wrs_opp_pts_off_tov, WrsOPPPTSPAINT = wrs_opp_pts_paint, WrsOPPREB = wrs_opp_reb, WrsOPPSTL = wrs_opp_stl, WrsOPPTOV = wrs_opp_tov ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team streak finder data for the given parameters available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_team.R
## Team Dashboard parameters are the same #' **Get WNBA Stats API Team Dashboard by Clutch Splits** #' @name wnba_teamdashboardbyclutch NULL #' @title #' **Get WNBA Stats API Team Dashboard by Clutch Splits** #' @rdname wnba_teamdashboardbyclutch #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Last10Sec3Point2TeamDashboard, #' Last10Sec3PointTeamDashboard, Last1Min5PointTeamDashboard, Last1MinPlusMinus5PointTeamDashboard, #' Last30Sec3Point2TeamDashboard, Last30Sec3PointTeamDashboard, Last3Min5PointTeamDashboard, #' Last3MinPlusMinus5PointTeamDashboard, Last5Min5PointTeamDashboard, #' Last5MinPlusMinus5PointTeamDashboard, OverallTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last5Min5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last3Min5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last1Min5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last30Sec3PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last10Sec3PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last5MinPlusMinus5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last3MinPlusMinus5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last1MinPlusMinus5PointTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last30Sec3Point2TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last10Sec3Point2TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @family WNBA Clutch Functions #' @details #' ```r #' wnba_teamdashboardbyclutch(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbyclutch <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbyclutch" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by clutch data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by Game Splits** #' @name wnba_teamdashboardbygamesplits NULL #' @title #' **Get WNBA Stats API Team Dashboard by Game Splits** #' @rdname wnba_teamdashboardbygamesplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ByActualMarginTeamDashboard, #' ByHalfTeamDashboard, ByPeriodTeamDashboard, ByScoreMarginTeamDashboard, #' OverallTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ByHalfTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ByPeriodTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ByScoreMarginTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ByActualMarginTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbygamesplits(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbygamesplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbygamesplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by game splits data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by General Splits** #' @name wnba_teamdashboardbygeneralsplits NULL #' @title #' **Get WNBA Stats API Team Dashboard by General Splits** #' @rdname wnba_teamdashboardbygeneralsplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: DaysRestTeamDashboard, #' LocationTeamDashboard, MonthTeamDashboard, OverallTeamDashboard, #' PrePostAllStarTeamDashboard, WinsLossesTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |SEASON_YEAR |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **LocationTeamDashboard** #' #' #' |col_name |types | #' |:------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_GAME_LOCATION |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **WinsLossesTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GAME_RESULT |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **MonthTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |SEASON_MONTH_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PrePostAllStarTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |SEASON_SEGMENT |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **DaysRestTeamDashboard** #' #' #' |col_name |types | #' |:--------------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_DAYS_REST_RANGE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbygeneralsplits(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbygeneralsplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbygeneralsplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by general splits data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by Last N Games** #' @name wnba_teamdashboardbylastngames NULL #' @title #' **Get WNBA Stats API Team Dashboard by Last N Games** #' @rdname wnba_teamdashboardbylastngames #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: GameNumberTeamDashboard, #' Last10TeamDashboard, Last15TeamDashboard, Last20TeamDashboard, #' Last5TeamDashboard, OverallTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last5TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last10TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last15TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Last20TeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **GameNumberTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbylastngames(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbylastngames <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbylastngames" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no teamdashboard by last n games data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by Opponent** #' @name wnba_teamdashboardbyopponent NULL #' @title #' **Get WNBA Stats API Team Dashboard by Opponent** #' @rdname wnba_teamdashboardbyopponent #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ConferenceTeamDashboard, #' DivisionTeamDashboard, OpponentTeamDashboard, OverallTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ConferenceTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **DivisionTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **OpponentTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbyopponent(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbyopponent <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbyopponent" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by opponent data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by Shooting Splits** #' @name wnba_teamdashboardbyshootingsplits NULL #' @title #' **Get WNBA Stats API Team Dashboard by Shooting Splits** #' @rdname wnba_teamdashboardbyshootingsplits #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: AssistedBy, #' AssitedShotTeamDashboard, OverallTeamDashboard, Shot5FTTeamDashboard, #' Shot8FTTeamDashboard, ShotAreaTeamDashboard, ShotTypeTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **Shot5FTTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **Shot8FTTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **ShotAreaTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **AssitedShotTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **ShotTypeTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' **AssistedBy** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |PLAYER_ID |character | #' |PLAYER_NAME |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |EFG_PCT |character | #' |BLKA |character | #' |PCT_AST_2PM |character | #' |PCT_UAST_2PM |character | #' |PCT_AST_3PM |character | #' |PCT_UAST_3PM |character | #' |PCT_AST_FGM |character | #' |PCT_UAST_FGM |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |EFG_PCT_RANK |character | #' |BLKA_RANK |character | #' |PCT_AST_2PM_RANK |character | #' |PCT_UAST_2PM_RANK |character | #' |PCT_AST_3PM_RANK |character | #' |PCT_UAST_3PM_RANK |character | #' |PCT_AST_FGM_RANK |character | #' |PCT_UAST_FGM_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @family WNBA Shooting Functions #' @details #' [Team Dashboard by Shooting Splits](https://www.nba.com/stats/team/1610612749/shooting) #' ```r #' wnba_teamdashboardbyshootingsplits(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbyshootingsplits <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbyshootingsplits" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by shooting splits data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard by Team Performance** #' @name wnba_teamdashboardbyteamperformance NULL #' @title #' **Get WNBA Stats API Team Dashboard by Team Performance** #' @rdname wnba_teamdashboardbyteamperformance #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: OverallTeamDashboard, #' PointsScoredTeamDashboard, PontsAgainstTeamDashboard, ScoreDifferentialTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ScoreDifferentialTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PointsScoredTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **PontsAgainstTeamDashboard** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE_ORDER |character | #' |GROUP_VALUE |character | #' |GROUP_VALUE_2 |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbyteamperformance(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbyteamperformance <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbyteamperformance" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by team performance data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard Year over Year** #' @name wnba_teamdashboardbyyearoveryear NULL #' @title #' **Get WNBA Stats API Team Dashboard Year over Year** #' @rdname wnba_teamdashboardbyyearoveryear #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: ByYearTeamDashboard, OverallTeamDashboard #' #' **OverallTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **ByYearTeamDashboard** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @details #' ```r #' wnba_teamdashboardbyyearoveryear(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashboardbyyearoveryear <- function( date_from = '', date_to = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashboardbyyearoveryear" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by year-over-year data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Team Dashboard - Lineups** #' @name wnba_teamdashlineups NULL #' @title #' **Get WNBA Stats API Team Dashboard - Lineups** #' @rdname wnba_teamdashlineups #' @author Saiem Gilani #' @param date_from date_from #' @param date_to date_to #' @param game_id game_id #' @param game_segment game_segment #' @param group_quantity group_quantity #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param measure_type measure_type #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param po_round po_round #' @param pace_adjust pace_adjust #' @param per_mode per_mode #' @param period period #' @param plus_minus plus_minus #' @param rank rank #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param shot_clock_range shot_clock_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a named list of data frames: Lineups, Overall #' #' **Overall** #' #' #' |col_name |types | #' |:-----------------|:---------| #' |GROUP_SET |character | #' |GROUP_VALUE |character | #' |TEAM_ID |character | #' |TEAM_ABBREVIATION |character | #' |TEAM_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' **Lineups** #' #' #' |col_name |types | #' |:---------------|:---------| #' |GROUP_SET |character | #' |GROUP_ID |character | #' |GROUP_NAME |character | #' |GP |character | #' |W |character | #' |L |character | #' |W_PCT |character | #' |MIN |character | #' |FGM |character | #' |FGA |character | #' |FG_PCT |character | #' |FG3M |character | #' |FG3A |character | #' |FG3_PCT |character | #' |FTM |character | #' |FTA |character | #' |FT_PCT |character | #' |OREB |character | #' |DREB |character | #' |REB |character | #' |AST |character | #' |TOV |character | #' |STL |character | #' |BLK |character | #' |BLKA |character | #' |PF |character | #' |PFD |character | #' |PTS |character | #' |PLUS_MINUS |character | #' |GP_RANK |character | #' |W_RANK |character | #' |L_RANK |character | #' |W_PCT_RANK |character | #' |MIN_RANK |character | #' |FGM_RANK |character | #' |FGA_RANK |character | #' |FG_PCT_RANK |character | #' |FG3M_RANK |character | #' |FG3A_RANK |character | #' |FG3_PCT_RANK |character | #' |FTM_RANK |character | #' |FTA_RANK |character | #' |FT_PCT_RANK |character | #' |OREB_RANK |character | #' |DREB_RANK |character | #' |REB_RANK |character | #' |AST_RANK |character | #' |TOV_RANK |character | #' |STL_RANK |character | #' |BLK_RANK |character | #' |BLKA_RANK |character | #' |PF_RANK |character | #' |PFD_RANK |character | #' |PTS_RANK |character | #' |PLUS_MINUS_RANK |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Team Functions #' @family WNBA Lineup Functions #' @details #' ```r #' wnba_teamdashlineups(team_id = '1611661328', season = most_recent_wnba_season()) #' ``` wnba_teamdashlineups <- function( date_from = '', date_to = '', game_id = '', game_segment = '', group_quantity = 5, last_n_games = 0, league_id = '10', location = '', measure_type = 'Base', month = 0, opponent_team_id = 0, outcome = '', pace_adjust = 'N', plus_minus = 'N', po_round = '', per_mode = 'Totals', period = 0, rank = 'N', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', shot_clock_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "teamdashlineups" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( DateFrom = date_from, DateTo = date_to, GameID = game_id, GameSegment = game_segment, GroupQuantity = group_quantity, LastNGames = last_n_games, LeagueID = league_id, Location = location, MeasureType = measure_type, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, PaceAdjust = pace_adjust, PORound = po_round, PerMode = per_mode, Period = period, PlusMinus = plus_minus, Rank = rank, Season = season, SeasonSegment = season_segment, SeasonType = season_type, ShotClockRange = shot_clock_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team dashboard by lineups data for {team_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_team_dash.R
#' **Get WNBA Stats API Video Details** #' @name wnba_videodetailsasset NULL #' @title #' **Get WNBA Stats API Video Details** #' @rdname wnba_videodetailsasset #' @author Saiem Gilani #' @param ahead_behind ahead_behind #' @param clutch_time clutch_time #' @param context_filter context_filter #' @param context_measure context_measure #' @param date_from date_from #' @param date_to date_to #' @param end_period end_period #' @param end_range end_range #' @param game_id game_id #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param period period #' @param player_id player_id #' @param point_diff point_diff #' @param position position #' @param range_type range_type #' @param rookie_year rookie_year #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param start_period start_period #' @param start_range start_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a list of tibbles: videoUrls, playlist #' #' **videoUrls** #' #' #' |col_name |types | #' |:--------|:---------| #' |uuid |character | #' |sdur |integer | #' |surl |character | #' |sth |character | #' |mdur |integer | #' |murl |character | #' |mth |character | #' |ldur |integer | #' |lurl |character | #' |lth |character | #' |vtt |character | #' |scc |character | #' |srt |character | #' #' **playlist** #' #' #' |col_name |types | #' |:--------|:---------| #' |gi |character | #' |ei |integer | #' |y |integer | #' |m |character | #' |d |character | #' |gc |character | #' |p |integer | #' |dsc |character | #' |ha |character | #' |hid |integer | #' |va |character | #' |vid |integer | #' |hpb |integer | #' |hpa |integer | #' |vpb |integer | #' |vpa |integer | #' |pta |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Video Functions #' @details #' ```r #' wnba_videodetailsasset(player_id = '1627668', team_id = '1611661328') #' ``` wnba_videodetailsasset <- function( ahead_behind = '', clutch_time = '', context_filter = '', context_measure = 'FGA', date_from = '', date_to = '', end_period = '', end_range = '', game_id = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', period = 0, player_id = '1627668', point_diff = '', position = '', range_type = '', rookie_year = '', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', start_period = '', start_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # Intentional # season_type <- gsub(' ', '+', season_type) version <- "videodetailsasset" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( AheadBehind = ahead_behind, ClutchTime = clutch_time, ContextFilter = context_filter, ContextMeasure = context_measure, DateFrom = date_from, DateTo = date_to, EndPeriod = end_period, EndRange = end_range, GameID = game_id, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, Period = period, PlayerID = player_id, PointDiff = point_diff, Position = position, RangeType = range_type, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, StartPeriod = start_period, StartRange = start_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) videoUrls <- resp$resultSets$Meta$videoUrls %>% data.frame() %>% dplyr::as_tibble() playlist <- resp$resultSets$playlist %>% data.frame() %>% dplyr::as_tibble() df_list <- c(list(videoUrls), list(playlist)) names(df_list) <- c("videoUrls", "playlist") }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no video detail assets data available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Video Details** #' @name wnba_videodetails NULL #' @title #' **Get WNBA Stats API Video Details** #' @rdname wnba_videodetails #' @author Saiem Gilani #' @param ahead_behind ahead_behind #' @param clutch_time clutch_time #' @param context_filter context_filter #' @param context_measure context_measure #' @param date_from date_from #' @param date_to date_to #' @param end_period end_period #' @param end_range end_range #' @param game_id game_id #' @param game_segment game_segment #' @param last_n_games last_n_games #' @param league_id league_id #' @param location location #' @param month month #' @param opponent_team_id opponent_team_id #' @param outcome outcome #' @param period period #' @param player_id player_id #' @param point_diff point_diff #' @param position position #' @param range_type range_type #' @param rookie_year rookie_year #' @param season season #' @param season_segment season_segment #' @param season_type season_type #' @param start_period start_period #' @param start_range start_range #' @param team_id team_id #' @param vs_conference vs_conference #' @param vs_division vs_division #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a list of tibbles: videoUrls, playlist #' #' **videoUrls** #' #' #' |col_name |types | #' |:--------|:---------| #' |uuid |character | #' |dur |logical | #' |stt |logical | #' |stp |logical | #' |sth |logical | #' |stw |logical | #' |mtt |logical | #' |mtp |logical | #' |mth |logical | #' |mtw |logical | #' |ltt |logical | #' |ltp |logical | #' |lth |logical | #' |ltw |logical | #' #' **playlist** #' #' #' |col_name |types | #' |:--------|:---------| #' |gi |character | #' |ei |integer | #' |y |integer | #' |m |character | #' |d |character | #' |gc |character | #' |p |integer | #' |dsc |character | #' |ha |character | #' |va |character | #' |hpb |integer | #' |hpa |integer | #' |vpb |integer | #' |vpa |integer | #' |pta |integer | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Video Functions #' @details #' ```r #' wnba_videodetails(player_id = '1627668', team_id = '1611661328') #' ``` wnba_videodetails <- function( ahead_behind = '', clutch_time = '', context_filter = '', context_measure = 'FGA', date_from = '', date_to = '', end_period = '', end_range = '', game_id = '', game_segment = '', last_n_games = 0, league_id = '10', location = '', month = 0, opponent_team_id = 0, outcome = '', period = 0, player_id = '1627668', point_diff = '', position = '', range_type = '', rookie_year = '', season = most_recent_wnba_season(), season_segment = '', season_type = 'Regular Season', start_period = '', start_range = '', team_id = '1611661328', vs_conference = '', vs_division = '', ...){ # season_type <- gsub(' ', '+', season_type) version <- "videodetails" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( AheadBehind = ahead_behind, ClutchTime = clutch_time, ContextFilter = context_filter, ContextMeasure = context_measure, DateFrom = date_from, DateTo = date_to, EndPeriod = end_period, EndRange = end_range, GameID = game_id, GameSegment = game_segment, LastNGames = last_n_games, LeagueID = league_id, Location = location, Month = month, OpponentTeamID = opponent_team_id, Outcome = outcome, Period = period, PlayerID = player_id, PointDiff = point_diff, Position = position, RangeType = range_type, RookieYear = rookie_year, Season = season, SeasonSegment = season_segment, SeasonType = season_type, StartPeriod = start_period, StartRange = start_range, TeamID = team_id, VsConference = vs_conference, VsDivision = vs_division ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) videoUrls <- resp$resultSets$Meta$videoUrls %>% data.frame() %>% dplyr::as_tibble() playlist <- resp$resultSets$playlist %>% data.frame() %>% dplyr::as_tibble() df_list <- c(list(videoUrls), list(playlist)) names(df_list) <- c("videoUrls", "playlist") }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no video details data available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Video Events** #' @name wnba_videoevents NULL #' @title #' **Get WNBA Stats API Video Events** #' @rdname wnba_videoevents #' @author Saiem Gilani #' @param game_id game_id #' @param game_event_id game_event_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a list of tibbles: videoUrls, playlist #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Video Functions #' @details #' ```r #' wnba_videoevents(game_id = '1022200075', game_event_id = '10') #' ``` wnba_videoevents <- function( game_id = '1022200075', game_event_id = '10', ...){ version <- "videoevents" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameID = game_id, GameEventID = game_event_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) videoUrls <- resp$resultSets$Meta$videoUrls %>% data.frame() %>% dplyr::as_tibble() playlist <- resp$resultSets$playlist %>% data.frame() %>% dplyr::as_tibble() df_list <- c(list(videoUrls), list(playlist)) names(df_list) <- c("videoUrls", "playlist") }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no video events data for {game_id} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } #' **Get WNBA Stats API Video Status** #' @name wnba_videostatus NULL #' @title #' **Get WNBA Stats API Video Status** #' @rdname wnba_videostatus #' @author Saiem Gilani #' @param game_date game_date #' @param league_id league_id #' @param ... Additional arguments passed to an underlying function like httr. #' @return Return a list of tibbles: VideoStatus #' #' **VideoStatus** #' #' #' |col_name |types | #' |:-------------------------|:---------| #' |GAME_ID |character | #' |GAME_DATE |character | #' |VISITOR_TEAM_ID |character | #' |VISITOR_TEAM_CITY |character | #' |VISITOR_TEAM_NAME |character | #' |VISITOR_TEAM_ABBREVIATION |character | #' |HOME_TEAM_ID |character | #' |HOME_TEAM_CITY |character | #' |HOME_TEAM_NAME |character | #' |HOME_TEAM_ABBREVIATION |character | #' |GAME_STATUS |character | #' |GAME_STATUS_TEXT |character | #' |IS_AVAILABLE |character | #' |PT_XYZ_AVAILABLE |character | #' #' @importFrom jsonlite fromJSON toJSON #' @importFrom dplyr filter select rename bind_cols bind_rows as_tibble #' @import rvest #' @export #' @family WNBA Video Functions #' @details #' ```r #' wnba_videostatus(game_date = '2022-06-10', league_id = '10') #' ``` wnba_videostatus <- function( game_date = '2022-06-10', league_id = '10', ...){ version <- "videostatus" endpoint <- wnba_endpoint(version) full_url <- endpoint params <- list( GameDate = game_date, LeagueID = league_id ) tryCatch( expr = { resp <- request_with_proxy(url = full_url, params = params, ...) df_list <- wnba_stats_map_result_sets(resp) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no video status data for {game_date} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
/scratch/gouwar.j/cran-all/cranData/wehoop/R/wnba_stats_video.R
# dinvweibull = function(x, shape, scale = 1, log = FALSE) { k <- max(lx<-length(x),lshape<-length(shape),lscale<-length(scale)) if (lx < k) x <- rep(x, length=k) if (lshape < k) shape <- rep(shape, length=k) if (lscale < k) scale <- rep(scale, length=k) #--- logd = numeric(k) id = (x > 0) logd[id] = log(shape[id])-log(scale[id]) - (shape[id]+1)*log(x[id]/scale[id]) - 1/(x[id]/scale[id])^shape[id] logd[!id] = -Inf #--- if(!is.null(Names <- names(x))) names(logd) = rep(Names,length=k) if (log) { return(logd) } else { return( exp(logd) ) } } # pinvweibull = function(q, shape, scale=1, lower.tail=TRUE, log.p=FALSE) { k <- max(lq<-length(q),lshape<-length(shape),lscale<-length(scale)) if (lq < k) q <- rep(q, length=k) if (lshape < k) shape <- rep(shape, length=k) if (lscale < k) scale <- rep(scale, length=k) #--- id = which(q > 0) p = numeric(length(q)) p[id] = pweibull(1/q[id], shape=shape[id], scale=1/scale[id], lower.tail=!lower.tail, log.p=log.p) if(!is.null(Names <- names(q))) names(p) = rep(Names,length=k) return(p) } # qinvweibull = function(p, shape, scale=1, lower.tail = TRUE, log.p = FALSE) { k <- max(lp<-length(p),lshape<-length(shape),lscale<-length(scale)) if (lp < k) p <- rep(p, length=k) if (lshape < k) shape <- rep(shape, length=k) if (lscale < k) scale <- rep(scale, length=k) q = 1/qweibull(p = p, shape = shape, scale = 1/scale, lower.tail = !lower.tail, log.p = log.p) if(!is.null(Names<-names(p))) names(q)<-rep(Names,length=k) return(q) } # rinvweibull = function(n, shape, scale=1) { lshape<-length(shape); lscale<-length(scale) if (lshape < n) shape <- rep(shape, length=n) if (lscale < n) scale <- rep(scale, length=n) 1/rweibull(n, shape=shape, scale=1/scale) } #
/scratch/gouwar.j/cran-all/cranData/weibullness/R/Distribution.inverse.Weibull.R
#------------------------------ # We need n when the data are right-censored at the max. obs gumbel.gp <- function(x,n, a){ ## It was a=0.5 x = sort(x) r = length(x) if ( missing(n) ) n=r if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } if ( n < r ) stop("n cannot be smaller than the number of observations") R = ppoints(n,a=a) LM=lm(-log(-log( R[1:r] ))~x) B = as.numeric( coef (LM) ) beta = 1/B[2] mu = -beta*B[1] structure(list(location=mu, scale=beta), class="gumbel.estimate") } #------------------------------ print.gumbel.estimate <- function(x, digits = getOption("digits"), ...) { ans = format(x, digits=digits) dn = dimnames(ans) print(ans, quote=FALSE) invisible(x) } #------------------------------
/scratch/gouwar.j/cran-all/cranData/weibullness/R/Estimate.Gumbel.R
# Based on Farnum/Booth:1997 weibull.mle <- function(x, threshold, interval, interval.threshold, extendInt="downX", a, tol=.Machine$double.eps^0.25, maxiter=1000, trace=0) { if (missing(threshold)) { threshold = weibull.threshold(x, a, interval.threshold, extendInt) } x = x - threshold ## TINY = .Machine$double.neg.eps ## if ( any (x < TINY) ) stop("The data should be positive") if (missing(interval)) { meanlog = mean(log(x)) lower = 1 / ( log(max(x)) - meanlog ) upper.rev = sum( (x^lower)*log(x) ) / sum( x^lower ) - meanlog upper = 1 / upper.rev if (is.nan(upper)) upper=.Machine$double.xmax^0.2 interval = c(lower,upper) } EEweibull = function(alpha,x) { TINY = .Machine$double.neg.eps xalpha = x^alpha if ( sum(xalpha) < TINY ) return( mean(log(x)) - 1/alpha - mean(log(x)) ) sum(log(x)*(xalpha)) / sum(xalpha) - 1/alpha - mean(log(x)) } tmp = uniroot(EEweibull, interval=interval, x=x, extendInt="upX", tol=tol,maxiter=maxiter,trace=trace) alpha = tmp$root beta = mean(x^alpha)^(1/alpha) structure(list(shape=alpha,scale=beta,threshold=threshold),class="weibull.estimate") } #------------------------------ # We need n when the data are right-censored at the max. obs weibull.wp <- function(x,n, a){ ## It was a=0.5 x = sort(x) r = length(x) if ( missing(n) ) n=r if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } if ( n < r ) stop("n cannot be smaller than the number of observations") R = 1-ppoints(n,a=a) LM=lm(log(-log( R[1:r] ))~log(x)) B = as.numeric( coef (LM) ) alpha = B[2] beta = exp(-B[1]/B[2]) structure(list(shape=alpha,scale=beta), class="weibull.estimate") } #------------------------------ weibull.rm <- function(x, a){ ## Repeated median (added on 2022-07-10) x = sort( log(unique(x)) ) n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } y = log(-log(1-ppoints(n, a=a))) DX = outer(x,x,"-"); DY = outer(y,y,"-") diag(DX) = NA alpha.hat = median( apply(DY/DX,2, median, na.rm=TRUE) ) # slope intercept = median(y-alpha.hat*x) # This intercept is better than the below. ## intercept = median( apply((outer(x,y,"*")-outer(y,x,"*"))/DX, 2, median, na.rm=TRUE) ) beta.hat = exp(-intercept/alpha.hat) structure( list(shape=alpha.hat, scale=beta.hat), class = "weibull.estimate") } #------------------------------ #------------------------------ weibull.threshold <- function(x, a, interval.threshold, extendInt="downX") { n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } EE.weibull.threshold = function(threshold) { x = sort(x) v = log(-log(1-ppoints(n,a=a))) u1= log(x-threshold) w = -1/(x-threshold) u0 = u1 - mean(u1) v0 = v - mean(v) w0 = w - mean(w) return( sum(w0*v0)/sum(u0*v0) - sum(u0*w0)/sum(u0*u0) ) } minx = min(x) TINY = .Machine$double.neg.eps^0.5 SD = mad(x) if (missing(interval.threshold)) { LOWER = minx - TINY - SD UPPER = minx - TINY interval.threshold = c(LOWER,UPPER) } tmp = uniroot(EE.weibull.threshold, interval=interval.threshold, extendInt=extendInt) ans = tmp$root names(ans) = "threshold" return(ans) } #------------------------------ #------------------------------ print.weibull.estimate <- function(x, digits = getOption("digits"), ...) { ans = format(x, digits=digits) dn = dimnames(ans) print(ans, quote=FALSE) invisible(x) } ################################################################### # Interval Censored ################################################################### # ================================================================= # Incomplete Upper Gamma Function #------------------------------------------------------------------ lGAMMA.incomplete = function(a,b) { if( a <= 0 ) a = .Machine$double.neg.eps return( pgamma(b,a,lower.tail=FALSE,log.p=TRUE) + lgamma(a) ) } GAMMA.incomplete = function(a,b) { exp(lGAMMA.incomplete(a,b)) } # ================================================================= # =================================================================== # Version : 1.0, Dec. 25, 2016 # 1.1, Feb. 14, 2020 # 1.2, Jan. 4, 2023 # NOTE: Euler-Mascheroni constant gam = -digamma(1) # =================================================================== U.i.s = function(kappa.s, theta.s, ai, bi) { TINY = .Machine$double.neg.eps if ( ai > bi ) return(0.0) if ( abs(bi-ai) < TINY ) return(log(ai)) t.ai = (ai/theta.s)^kappa.s exp.t.ai = exp(-t.ai) t.bi = (bi/theta.s)^kappa.s exp.t.bi = exp(-t.bi) D.i.s = exp.t.ai - exp.t.bi if (ai>0) { tmpai = log(ai)*exp.t.ai + GAMMA.incomplete(0,t.ai)/kappa.s } else { tmpai = log(theta.s) + digamma(1)/kappa.s } BIG = .Machine$double.xmax^0.2 if (bi >= BIG) { ## .Machine$double.xmax tmpbi = 0 } else { tmpbi = log(bi)*exp.t.bi + GAMMA.incomplete(0,t.bi)/kappa.s } return( (tmpai-tmpbi)/D.i.s ) } # U.i.s.0.inf = function(kappa.s, theta.s) { log(theta.s) + digamma(1)/kappa.s } # # U.i.s (2, 3, 0, Inf); U.i.s.0.inf(2, 3) # U.i.s (2, 3, 3, 3); U.i.s (2, 3, 3, 3.000) U.i.s.0.bi = function(kappa.s, theta.s, bi) { A = log(theta.s) + digamma(1)/kappa.s t.bi = (bi/theta.s)^kappa.s tmp = log(bi)*exp(-t.bi) + GAMMA.incomplete(0, t.bi)/kappa.s (A - tmp) / (1- exp(-t.bi)) ## A /(1- exp(-t.bi)) - tmp/exp(-t.bi) } # U.i.s (2,3, 0.0, 3) ; U.i.s.0.bi(2,3, 3) # U.i.s.ai.inf = function(kappa.s, theta.s, ai) { t.ai = (ai/theta.s)^kappa.s tmp = log(ai)*exp(-t.ai) + GAMMA.incomplete(0, t.ai)/kappa.s tmp / exp(-t.ai) } # U.i.s (2, 3, 1, Inf) ; U.i.s.ai.inf(2,3,1) # =================================================================== # Version : 1.0, Dec. 25, 2016 # 1.1, Feb. 14, 2020 # 1.2, Jan. 4, 2023 # NOTE: Euler-Mascheroni constant gam = -digamma(1) # =================================================================== V.i.s = function(kappa, kappa.s, theta.s, ai, bi) { TINY = .Machine$double.neg.eps if ( ai > bi ) return(0.0) if ( abs(bi-ai) < TINY ) return(ai^kappa) t.ai = (ai/theta.s)^kappa.s t.bi = (bi/theta.s)^kappa.s D.i.s = exp(-t.ai) - exp(-t.bi) tmpai = GAMMA.incomplete( (kappa+kappa.s)/kappa.s, (ai/theta.s)^kappa.s ) tmpbi = GAMMA.incomplete( (kappa+kappa.s)/kappa.s, (bi/theta.s)^kappa.s ) theta.s^kappa * (tmpai-tmpbi)/D.i.s } # V.i.s (1, 2, 3, 1, Inf); V.i.s (1, 2, 3, 0, Inf); V.i.s (1, 2, 3, 0, 4) # V.i.s (1, 2, 3, 9, 9); V.i.s (1, 2, 3, 8.9999, 9) # V.i.s (1, 2, 3, 1, 1); V.i.s (1, 2, 3, 0.9999, 1) ################################################################## ## V.i.s = function(kappa, kappa.s, theta.s, ai, bi) ## U.i.s = function(kappa.s, theta.s, ai, bi) weibull.ic = function(X, start=c(1,1), maxits=10000, eps=1E-5){ kappa = start[1] theta = start[2] ij = dim(X) n = ij[1] if ( ij[2] > 2 ) stop(" Warning: The data X should be n x 2 matrix.") if ( any(X[,1] > X[,2]) ) stop(" Warning: The data should satisfy a <= b."); iter = 0 converged = FALSE # Start the EM colnames(X) = NULL; rownames(X) = NULL ai = X[,1]; bi = X[,2] fn = function(newkappa) { sumU.i.s = 0 sumV.i.s = 0 for ( i in seq_len(n) ) sumU.i.s = sumU.i.s + U.i.s(kappa, theta, ai[i], bi[i]) for ( i in seq_len(n) ) sumV.i.s = sumV.i.s + V.i.s(newkappa, kappa, theta, ai[i], bi[i]) -1 * ( n*log(newkappa) + newkappa*sumU.i.s - n*log(sumV.i.s) ) } while( (iter<maxits)&(!converged) ) { OPT = nlm(fn, kappa); newkappa = OPT$estimate ## OPT = nlminb(kappa,fn); newkappa = OPT$par meanV.i.s = 0 for ( i in seq_len(n) ) meanV.i.s = meanV.i.s + V.i.s(newkappa, kappa, theta, ai[i], bi[i])/n newtheta = meanV.i.s^(1/newkappa) # assess convergence converged = (abs(newkappa-kappa)<eps*abs(newkappa)) & (abs(newtheta -theta)<eps*abs(newtheta)) iter = iter+1 kappa = newkappa theta = newtheta } list( shape=newkappa, scale=newtheta, iter=iter, conv=converged ) } ###################################################################
/scratch/gouwar.j/cran-all/cranData/weibullness/R/Estimate.Weibull.R
################################################################### # Inverse Weibull ################################################################### invweibull.mle <- function(x, interval, tol = .Machine$double.eps^0.25, maxiter = 1000, trace = 0 ) { y = 1/x if (missing(interval)) { meanlog = mean(log(y)) lower = 1 / ( log(max(y)) - meanlog ) upper.rev = sum( (y^lower)*log(y) ) / sum( y^lower ) - meanlog upper = 1 / upper.rev if (is.nan(upper)) upper=.Machine$double.xmax^0.2 interval = c(lower,upper) } EEweibull = function(beta,y) { TINY = .Machine$double.neg.eps ybeta = y^beta if ( sum(ybeta) < TINY ) return( mean(log(y)) - 1/beta - mean(log(y)) ) sum(log(y)*(ybeta)) / sum(ybeta) - 1/beta - mean(log(y)) } tmp = uniroot(EEweibull, interval=interval, y=y,tol=tol, extendInt="upX", maxiter=maxiter,trace=trace) beta = tmp$root theta = 1 / mean(y^beta)^(1/beta) structure(list(shape = beta, scale = theta, threshold = 0), class = "weibull.estimate") }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/Estimate.inverse.Weibull.R
globalVariables("Exponential.ANOVA.Quantiles") # Exponential GOF Test from the Exponential ANOVA ep.test <- function (x,a) { DNAME = deparse(substitute(x)) stopifnot(is.numeric(x)) x = sort(x[complete.cases(x)]) n = length(x) if ((n < 3L || n > 1000L)) stop("sample size must be between 3 and 1000") if (missing(a)) {a= ifelse(n <= 10, 3/8, 1/2)} w = n /(n-1) * (mean(x)-min(x))^2 / ((n-1)*var(x)) alphas = as.numeric( colnames(Exponential.ANOVA.Quantiles) ) quantiles = Exponential.ANOVA.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = (1-pvalue.function(w)) ## <- RVAL = list(statistic = c(W=w), p.value = pval, sample.size=n, method = "Exponential GOF test from ANOVA for Exponential", data.name = DNAME) class(RVAL) = "htest" return(RVAL) } ## ep.test(1:3) # p-value with w and n ep.test.pvalue <- function (w,n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") alphas = as.numeric( colnames(Exponential.ANOVA.Quantiles) ) quantiles = Exponential.ANOVA.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = (1-pvalue.function(w)) ## <- RVAL = list(statistic = c(W = w), p.value = pval, method = "p-value value for the Exponential GOF test", data.name = NULL) class(RVAL) = "htest" return(RVAL) } # critical value with alpha and n ep.test.critical <- function (alpha, n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") if (alpha <= 0 || alpha >= 1) stop("Significance level must be between 0 and 1") alpha = (1-alpha) ### AL = as.integer( round(alpha*1000) ) alphas = as.numeric( colnames(Exponential.ANOVA.Quantiles) ) quantiles = Exponential.ANOVA.Quantiles[n-2,AL+1] RVAL = list(sample.size=n, alpha= (1-AL/1000), critical.value=quantiles, title="Critical value for the Exponential GOF test", data.name =Exponential.ANOVA.Quantiles) class(RVAL) = "ep.test.critical" return(RVAL) } ## critical value for ep.test print.ep.test.critical <- function (x,...) { cat("\n ", x$title, "\n\n") cat("significance level = ",x$alpha, ", ", "sample size = ", x$sample.size,"\n\n",sep="" ) cat("critical value =", x$critical.value, "\n\n") }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/ep.test.R
globalVariables("Gumbel.Plot.Quantiles") # Gumbel Probability Plot gp.test <- function (x,a) { DNAME = deparse(substitute(x)) stopifnot(is.numeric(x)) x = sort(x[complete.cases(x)]) n = length(x) if ((n < 3L || n > 1000L)) stop("sample size must be between 3 and 1000") if (missing(a)) {a= ifelse(n <= 10, 3/8, 1/2)} u = x v =-log(-log(ppoints(n,a=a))) r = cor(u,v) alphas = as.numeric( colnames(Gumbel.Plot.Quantiles) ) quantiles = Gumbel.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation=r), p.value = pval, sample.size=n, method = "Gumbel goodness-of-fit test from the Gumbel probability plot", data.name = DNAME) class(RVAL) = "htest" return(RVAL) } ## gp.test(1:3) # p-value with r and n gp.test.pvalue <- function (r,n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") alphas = as.numeric( colnames(Gumbel.Plot.Quantiles) ) quantiles = Gumbel.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation = r), p.value = pval, method = "p-value value for the Gumbel goodness-of-fit test", data.name = NULL) class(RVAL) = "htest" return(RVAL) } ## critical value for gp.test print.gp.test.critical <- function (x,...) { cat("\n ", x$title, "\n\n") cat("significance level = ",x$alpha, ", ", "sample size = ", x$sample.size,"\n\n",sep="" ) cat("critical value =", x$critical.value, "\n\n") } # critical value with alpha and n gp.test.critical <- function (alpha, n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") if (alpha <= 0 || alpha >= 1) stop("Significance level must be between 0 and 1") AL = as.integer( round(alpha*1000) ) alphas = as.numeric( colnames(Gumbel.Plot.Quantiles) ) quantiles = Gumbel.Plot.Quantiles[n-2,AL+1] RVAL = list(sample.size=n, alpha=AL/1000, critical.value=quantiles, title="Critical value for the Gumbel goodness-of-fit test", data.name =Gumbel.Plot.Quantiles) class(RVAL) = "gp.test.critical" return(RVAL) }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/gp.test.R
globalVariables("IW.Plot.Quantiles") # Inverse Weibullness Test from the inverse Weibull Plot iwp.test <- function (x,a) { DNAME = deparse(substitute(x)) stopifnot(is.numeric(x)) x = sort(x[complete.cases(x)]) n = length(x) if ((n < 3L || n > 1000L)) stop("sample size must be between 3 and 1000") if (missing(a)) {a= ifelse(n <= 10, 3/8, 1/2)} u = log( x ) v = -log(-log(ppoints(n,a=a))) r = cor(u,v) alphas = as.numeric( colnames(IW.Plot.Quantiles) ) quantiles = IW.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation=r), p.value = pval, sample.size=n, method = "Inverse Weibullness test from the inverse Weibull plot", data.name = DNAME) class(RVAL) = "htest" return(RVAL) } ## iwp.test(1:3) # p-value with r and n iwp.test.pvalue <- function (r,n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") alphas = as.numeric( colnames(IW.Plot.Quantiles) ) quantiles = IW.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation = r), p.value = pval, method = "p-value value for the inverse Weibullness test", data.name = NULL) class(RVAL) = "htest" return(RVAL) } ## critical value for iwp.test print.iwp.test.critical <- function (x,...) { cat("\n ", x$title, "\n\n") cat("significance level = ",x$alpha, ", ", "sample size = ", x$sample.size,"\n\n",sep="" ) cat("critical value =", x$critical.value, "\n\n") } # critical value with alpha and n iwp.test.critical <- function (alpha, n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") if (alpha <= 0 || alpha >= 1) stop("Significance level must be between 0 and 1") AL = as.integer( round(alpha*1000) ) alphas = as.numeric( colnames(IW.Plot.Quantiles) ) quantiles = IW.Plot.Quantiles[n-2,AL+1] RVAL = list(sample.size=n, alpha=AL/1000, critical.value=quantiles, title="Critical value for the inverse Weibullness test", data.name = IW.Plot.Quantiles) class(RVAL) = "iwp.test.critical" return(RVAL) }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/iwp.test.R
############################################################################### # Weibull Plot wp.plot <- function(x, plot.it=TRUE, a, col.line="black", lty.line=1, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab="Probability", ...) { x = sort(x[complete.cases(x)]) n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } y = log(-log(1-ppoints(n,a=a))) if (plot.it) { plot(x,y, log="x", yaxt="n", xlim=xlim, ylim=ylim, main=main, sub=sub, xlab=xlab, ylab=ylab, ...) ticklabels=c( (1:5)/100, (1:9)/10) ticksat=log(-log(1-ticklabels)) axis(2,at=ticksat,labels=ticklabels) LM = lm(y~log(x)) curve( predict(LM,newdata=data.frame(x)), add=TRUE, lty=lty.line, col=col.line) } invisible(list(x=x, y=y)) } ############################################################################### # Inverse Weibull Probability Plot iwp.plot <- function(x, plot.it=TRUE, a, col.line="black", lty.line=1, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab="Probability", ...) { x = sort(x[complete.cases(x)]) n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } y = -log(-log(ppoints(n,a=a))) if (plot.it) { plot(x,y, log="x", yaxt="n", xlim=xlim, ylim=ylim, main=main, sub=sub, xlab=xlab, ylab=ylab, ...) ticklabels=c( (1:5)/100, (1:9)/10) ticksat=-log(-log(ticklabels)) axis(2,at=ticksat,labels=ticklabels) LM = lm(y~log(x)) curve( predict(LM,newdata=data.frame(x)), add=TRUE, lty=lty.line, col=col.line) } invisible(list(x=x, y=y)) } ############################################################################### # Exponential Probability Plot ep.plot <- function(x, plot.it=TRUE, a, col.line="black", lty.line=1, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab="Probability", ...) { x = sort(x[complete.cases(x)]) n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } y = -log(1-ppoints(n,a=a)) if (plot.it) { plot(x,y, yaxt="n", xlim=xlim, ylim=ylim, main=main, sub=sub, xlab=xlab, ylab=ylab, ...) ticklabels=c(0.01, (1:9)/10, 0.99) ticksat=-log(1-ticklabels) axis(2,at=ticksat,labels=ticklabels) LM = lm(y~0+x) curve( predict(LM,newdata=data.frame(x)), add=TRUE, lty=lty.line, col=col.line) } invisible(list(x=x, y=y)) } ############################################################################### # Gumbel Probability Plot gp.plot <- function(x, plot.it=TRUE, a, col.line="black", lty.line=1, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab="Probability", ...) { x = sort(x[complete.cases(x)]) n = length(x) if (missing(a)) { a = ifelse(n <= 10, 3/8, 1/2) } y = -log(-log(ppoints(n,a=a))) if (plot.it) { plot(x,y, yaxt="n", xlim=xlim, ylim=ylim, main=main, sub=sub, xlab=xlab, ylab=ylab, ...) ticklabels=c(0.01, (1:9)/10, 0.99) ticksat=-log(-log(ticklabels)) axis(2,at=ticksat,labels=ticklabels) LM = lm(y~x) curve( predict(LM,newdata=data.frame(x)), add=TRUE, lty=lty.line, col=col.line) } invisible(list(x=x, y=y)) } ###############################################################################
/scratch/gouwar.j/cran-all/cranData/weibullness/R/prob.plot.R
globalVariables("Weibull.Plot.Quantiles") # Weibullness Test from the Weibull Plot wp.test <- function (x,a) { DNAME = deparse(substitute(x)) stopifnot(is.numeric(x)) x = sort(x[complete.cases(x)]) n = length(x) if ((n < 3L || n > 1000L)) stop("sample size must be between 3 and 1000") if (missing(a)) {a= ifelse(n <= 10, 3/8, 1/2)} u = log( x ) v = log(-log(1-ppoints(n,a=a))) r = cor(u,v) alphas = as.numeric( colnames(Weibull.Plot.Quantiles) ) quantiles = Weibull.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation=r), p.value = pval, sample.size=n, method = "Weibullness test from the Weibull plot", data.name = DNAME) class(RVAL) = "htest" return(RVAL) } ## wp.test(1:3) # p-value with r and n wp.test.pvalue <- function (r,n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") alphas = as.numeric( colnames(Weibull.Plot.Quantiles) ) quantiles = Weibull.Plot.Quantiles[n-2,] pvalue.function = approxfun(x=quantiles, y=alphas, yleft=0.0, yright=1.0) pval = pvalue.function(r) RVAL = list(statistic = c(correlation = r), p.value = pval, method = "p-value value for the Weibullness test", data.name = NULL) class(RVAL) = "htest" return(RVAL) } ## critical value for wp.test print.wp.test.critical <- function (x,...) { cat("\n ", x$title, "\n\n") cat("significance level = ",x$alpha, ", ", "sample size = ", x$sample.size,"\n\n",sep="" ) cat("critical value =", x$critical.value, "\n\n") } # critical value with alpha and n wp.test.critical <- function (alpha, n) { if (n < 3L || n > 1000L) stop("sample size must be between 3 and 1000") if (alpha <= 0 || alpha >= 1) stop("Significance level must be between 0 and 1") AL = as.integer( round(alpha*1000) ) alphas = as.numeric( colnames(Weibull.Plot.Quantiles) ) quantiles = Weibull.Plot.Quantiles[n-2,AL+1] RVAL = list(sample.size=n, alpha=AL/1000, critical.value=quantiles, title="Critical value for the Weibullness test", data.name =Weibull.Plot.Quantiles) class(RVAL) = "wp.test.critical" return(RVAL) }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/wp.test.R
#.onAttach <- function(...){ cat("\n weibullness Package is installed. \n\n") } .onAttach <- function(...){ packageStartupMessage("\n weibullness Package is installed. \n\n") }
/scratch/gouwar.j/cran-all/cranData/weibullness/R/zzz.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 getLambda <- function(x, weights, status, beta) { .Call(`_weibulltools_getLambda`, x, weights, status, beta) } g <- function(x, weights, status, beta) { .Call(`_weibulltools_g`, x, weights, status, beta) } gDiv <- function(x, weights, beta) { .Call(`_weibulltools_gDiv`, x, weights, beta) } NewtonRaphson <- function(x, weights, status) { .Call(`_weibulltools_NewtonRaphson`, x, weights, status) } MStepWeibull <- function(x, posterior, status) { .Call(`_weibulltools_MStepWeibull`, x, posterior, status) } weibullDensity <- function(x, beta, lambda, censored) { .Call(`_weibulltools_weibullDensity`, x, beta, lambda, censored) } LikelihoodWeibull <- function(x, parameter, status, prior, P, logL) { invisible(.Call(`_weibulltools_LikelihoodWeibull`, x, parameter, status, prior, P, logL)) } normalize <- function(M) { invisible(.Call(`_weibulltools_normalize`, M)) } #' EM-Algorithm using Newton-Raphson Method #' #' This method uses the EM-Algorithm to estimate the parameters of a univariate #' mixture model. Until now, the mixture model can consist of k two-parametric #' Weibull distributions. The Weibull distributions are parameterized with scale #' \eqn{\eta} and shape \eqn{\beta}. In M-step these parameters are estimated using #' Newton-Raphson. This function is implemented in c++ and is called in function #' \code{\link{mixmod_em}}. #' #' @encoding UTF-8 #' @references Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by #' Failure Mode, Quality Progress, 35(6), 47-52, 2002 #' #' @param x a numeric vector which consists of lifetime data. Lifetime #' data could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param status a vector of binary data (0 or 1) indicating whether unit \emph{i} #' is a right censored observation (= 0) or a failure (= 1). #' @param post a numeric matrix specifying initial a-posteriori probabilities. #' The number of rows have to be in line with observations \code{x} and the #' number of columns must equal the mixture components \code{k}. #' @param distribution supposed distribution of mixture model components. #' The value must be \code{"weibull"}. Other distributions have not been #' implemented yet. #' @param k integer of mixture components, default is 2. #' @param method default method is \code{"EM"}. Other methods have not been #' implemented yet. #' @param n_iter integer defining the maximum number of iterations. #' @param conv_limit numeric value defining the convergence limit. #' #' @return Returns a list with the following components: #' \itemize{ #' \item \code{coefficients} : A matrix with estimated Weibull parameters. In the #' first row the estimated scale parameters \eqn{\eta} and in the second the #' estimated shape parameters \eqn{\beta} are provided. The first column belongs #' to the first mixture component and so forth. #' \item \code{posteriori} : A matrix with estimated a-posteriori probabilities. #' \item \code{priori} : A vector with estimated a-priori probabilities. #' \item \code{logL} : The value of the complete log-likelihood.} #' #' @keywords internal mixture_em_cpp <- function(x, status, post, distribution = "weibull", k = 2L, method = "EM", n_iter = 100L, conv_limit = 1e-6) { .Call(`_weibulltools_mixture_em_cpp`, x, status, post, distribution, k, method, n_iter, conv_limit) } #' Computation of Johnson Ranks #' #' This function calculates the Johnson ranks which are used to estimate the #' failure probabilities in case of (multiple) right censored data. #' #' @param f a numeric vector indicating the number of failed units for a #' specific realization of the lifetime characteristic. #' @param n_out a numeric vector indicating the number of failed and censored #' units that have a shorter realization of lifetime characteristic as unit #' \emph{i}. #' @param n an integer value indicating the sample size. #' #' @return A numeric vector containing the computed Johnson ranks. #' #' @keywords internal calculate_ranks <- function(f, n_out, n) { .Call(`_weibulltools_calculate_ranks`, f, n_out, n) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/RcppExports.R
#' Beta Binomial Confidence Bounds for Quantiles and Probabilities #' #' @description #' This function computes the non-parametric beta binomial confidence bounds (BB) #' for quantiles and failure probabilities. #' #' @details The procedure is similar to the *Median Ranks* method but with the #' difference that instead of finding the probability for the *j*-th rank at the #' 50% level the probability (probabilities) has (have) to be found at the given #' confidence level. #' #' @param x A list with class `wt_model` (and further classes) returned by #' [rank_regression]. #' @param b_lives A numeric vector indicating the probabilities \eqn{p} of the #' \eqn{B_p}-lives (quantiles) to be considered. #' @param bounds A character string specifying the bound(s) to be computed. #' @param conf_level Confidence level of the interval. #' @param direction A character string specifying the direction of the confidence #' interval. `"y"` for failure probabilities or `"x"` for quantiles. #' @template dots #' #' @template return-bb-confidence-intervals #' @templateVar #' cdf_estimation_method Method for the estimation of failure probabilities which was specified in [estimate_cdf]. #' @return #' Further information is stored in the attributes of this tibble: #' #' * `distribution` : Distribution which was specified in [rank_regression]. #' * `bounds` : Specified bound(s). #' * `direction` : Specified direction. #' * `model_estimation` : Input list with class `wt_model`. #' #' @examples #' # Reliability data preparation: #' ## Data for two-parametric model: #' data_2p <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' ## Data for three-parametric model: #' data_3p <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Probability estimation: #' prob_tbl_2p <- estimate_cdf( #' data_2p, #' methods = "johnson" #' ) #' #' prob_tbl_3p <- estimate_cdf( #' data_3p, #' methods = "johnson" #' ) #' #' prob_tbl_mult <- estimate_cdf( #' data_3p, #' methods = c("johnson", "mr") #' ) #' #' # Model estimation with rank_regression(): #' rr_2p <- rank_regression( #' prob_tbl_2p, #' distribution = "weibull" #' ) #' #' rr_3p <- rank_regression( #' prob_tbl_3p, #' distribution = "lognormal3", #' conf_level = 0.90 #' ) #' #' rr_lists <- rank_regression( #' prob_tbl_mult, #' distribution = "loglogistic3", #' conf_level = 0.90 #' ) #' #' # Example 1 - Two-sided 95% confidence interval for probabilities ('y'): #' conf_betabin_1 <- confint_betabinom( #' x = rr_2p, #' bounds = "two_sided", #' conf_level = 0.95, #' direction = "y" #' ) #' #' # Example 2 - One-sided lower/upper 90% confidence interval for quantiles ('x'): #' conf_betabin_2_1 <- confint_betabinom( #' x = rr_2p, #' bounds = "lower", #' conf_level = 0.90, #' direction = "x" #' ) #' #' conf_betabin_2_2 <- confint_betabinom( #' x = rr_2p, #' bounds = "upper", #' conf_level = 0.90, #' direction = "x" #' ) #' #' # Example 3 - Two-sided 90% confidence intervals for both directions using #' # a three-parametric model: #' conf_betabin_3_1 <- confint_betabinom( #' x = rr_3p, #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "y" #' ) #' #' conf_betabin_3_2 <- confint_betabinom( #' x = rr_3p, #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "x" #' ) #' #' # Example 4 - Confidence intervals if multiple methods in estimate_cdf, i.e. #' # "johnson" and "mr", were specified: #' #' conf_betabin_4 <- confint_betabinom( #' x = rr_lists, #' bounds = "two_sided", #' conf_level = 0.99, #' direction = "y" #' ) #' #' @md #' #' @export confint_betabinom <- function(x, ...) { UseMethod("confint_betabinom") } #' @rdname confint_betabinom #' #' @export confint_betabinom.wt_model <- function(x, b_lives = c(0.01, 0.1, 0.50), bounds = c( "two_sided", "lower", "upper" ), conf_level = 0.95, direction = c("y", "x"), ... ) { stopifnot( inherits(x, "wt_model_estimation") || inherits(x, "wt_model_estimation_list") ) NextMethod() } #' @export confint_betabinom.wt_model_estimation <- function(x, b_lives = c(0.01, 0.1, 0.50), bounds = c( "two_sided", "lower", "upper" ), conf_level = 0.95, direction = c("y", "x"), ... ) { bounds <- match.arg(bounds) direction <- match.arg(direction) confint_betabinom_( model_estimation = x, b_lives = b_lives, bounds = bounds, conf_level = conf_level, direction = direction ) } #' @export confint_betabinom.wt_model_estimation_list <- function( x, b_lives = c(0.01, 0.1, 0.50), bounds = c("two_sided", "lower", "upper"), conf_level = 0.95, direction = c("y", "x"), ... ) { bounds <- match.arg(bounds) direction <- match.arg(direction) confint <- purrr::map_dfr(x, function(model_estimation) { confint <- confint_betabinom_( model_estimation = model_estimation, b_lives = b_lives, bounds = bounds, conf_level = conf_level, direction = direction ) }) attr(confint, "model_estimation") <- x confint } #' Beta Binomial Confidence Bounds for Quantiles and Probabilities #' #' @inherit confint_betabinom description details #' #' @inheritParams rank_regression.default #' @inheritParams confint_betabinom #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param dist_params The parameters (`coefficients`) returned by [rank_regression]. #' @param distribution Supposed distribution of the random variable. Has to be in #' line with the specification made in [rank_regression]. #' #' @template return-bb-confidence-intervals #' @templateVar #' cdf_estimation_method A character that is always `NA_character`. Only needed for internal use. #' @return #' Further information is stored in the attributes of this tibble: #' #' * `distribution` : Distribution which was specified in [rank_regression]. #' * `bounds` : Specified bound(s). #' * `direction` : Specified direction. #' #' @seealso [confint_betabinom] #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' status_1 <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' #' cycles <- alloy$cycles #' status_2 <- alloy$status #' #' # Probability estimation: #' prob_tbl <- estimate_cdf( #' x = obs, #' status = status_1, #' method = "johnson" #' ) #' #' prob_tbl_2 <- estimate_cdf( #' x = cycles, #' status = status_2, #' method = "johnson" #' ) #' #' # Model estimation with rank_regression(): #' rr <- rank_regression( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' distribution = "weibull", #' conf_level = 0.9 #' ) #' #' rr_2 <- rank_regression( #' x = prob_tbl_2$x, #' y = prob_tbl_2$prob, #' status = prob_tbl_2$status, #' distribution = "lognormal3" #' ) #' #' # Example 1 - Two-sided 95% confidence interval for probabilities ('y'): #' conf_betabin_1 <- confint_betabinom( #' x = prob_tbl$x, #' status = prob_tbl$status, #' dist_params = rr$coefficients, #' distribution = "weibull", #' bounds = "two_sided", #' conf_level = 0.95, #' direction = "y" #' ) #' #' # Example 2 - One-sided lower/upper 90% confidence interval for quantiles ('x'): #' conf_betabin_2_1 <- confint_betabinom( #' x = prob_tbl$x, #' status = prob_tbl$status, #' dist_params = rr$coefficients, #' distribution = "weibull", #' bounds = "lower", #' conf_level = 0.9, #' direction = "x" #' ) #' #' conf_betabin_2_2 <- confint_betabinom( #' x = prob_tbl$x, #' status = prob_tbl$status, #' dist_params = rr$coefficients, #' distribution = "weibull", #' bounds = "upper", #' conf_level = 0.9, #' direction = "x" #' ) #' #' # Example 3 - Two-sided 90% confidence intervals for both directions using #' # a three-parametric model: #' #' conf_betabin_3_1 <- confint_betabinom( #' x = prob_tbl_2$x, #' status = prob_tbl_2$status, #' dist_params = rr_2$coefficients, #' distribution = "lognormal3", #' bounds = "two_sided", #' conf_level = 0.9, #' direction = "y" #' ) #' #' conf_betabin_3_2 <- confint_betabinom( #' x = prob_tbl_2$x, #' status = prob_tbl_2$status, #' dist_params = rr_2$coefficients, #' distribution = "lognormal3", #' bounds = "two_sided", #' conf_level = 0.9, #' direction = "x" #' ) #' #' @md #' #' @export confint_betabinom.default <- function(x, status, dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), b_lives = c(0.01, 0.1, 0.50), bounds = c("two_sided", "lower", "upper"), conf_level = 0.95, direction = c("y", "x"), ... ) { bounds <- match.arg(bounds) direction <- match.arg(direction) distribution <- match.arg(distribution) # Construct fake wt_model_estimation: model_estimation <- list( data = tibble::tibble( x = x, status = status, cdf_estimation_method = NA_character_ ), coefficients = dist_params, distribution = distribution ) confint_betabinom_( model_estimation = model_estimation, b_lives = b_lives, bounds = bounds, conf_level = conf_level, direction = direction ) } confint_betabinom_ <- function(model_estimation, b_lives, bounds, conf_level, direction ) { # Prepare function inputs: x <- model_estimation$data$x status <- model_estimation$data$status distribution <- model_estimation$distribution ## Information of survived units are indirectly included in dist_params and n: dist_params <- model_estimation$coefficients n <- length(x) ## Only range of failed units is considered: x_ob <- x[status == 1] # Step 1: Determine x-y ranges and add the appropriate B_p-lives: x_y_b_lives <- add_b_lives(x_ob, dist_params, distribution, b_lives) x_seq <- x_y_b_lives$x_seq y_seq <- x_y_b_lives$y_seq # Step 2: Confidence intervals w.r.t 'direction' and 'bounds': ## Obtain virtual ranks by interpolation using Benard's formula: virt_rank <- y_seq * (n + 0.4) + 0.3 ## Confidence intervals for direction = "y" w.r.t 'bounds': list_confint <- conf_bb_y( y = y_seq, n = n, r = virt_rank, bounds = bounds, conf_level = conf_level ) ## Confidence intervals for direction = "x" if needed: if (direction == "x") { list_confint <- purrr::map( list_confint, predict_quantile, dist_params = dist_params, distribution = distribution ) } # Step 3: Form output: list_output <- c( list(x = x_seq, rank = virt_rank, prob = y_seq), list_confint ) tbl_out <- tibble::as_tibble(list_output) ## Add cdf_estimation_method as column to support different cdf_estimation_methods: cdf_estimation_method <- model_estimation$data$cdf_estimation_method[1] tbl_out$cdf_estimation_method <- cdf_estimation_method # recycling! tbl_out <- structure( tbl_out, distribution = distribution, bounds = bounds, direction = direction ) ## Only add model_estimation if not faked by .default: if (inherits(model_estimation, "wt_model_estimation")) { attr(tbl_out, "model_estimation") <- model_estimation } ## Make output usable for generics: class(tbl_out) <- c("wt_confint", class(tbl_out)) tbl_out } #' Fisher's Confidence Bounds for Quantiles and Probabilities #' #' @description #' This function computes normal-approximation confidence intervals for quantiles #' and failure probabilities. #' #' @details #' The basis for the calculation of these confidence bounds are the standard errors #' obtained by the [delta method][delta_method]. #' #' The bounds on the probability are determined by the *z-procedure*. See #' 'References' for more information on this approach. #' #' @inheritParams confint_betabinom #' @param x A list with classes `wt_model` and `wt_ml_estimation` returned by #' [ml_estimation]. #' #' @template return-fisher-confidence-intervals #' @return #' Further information is stored in the attributes of this tibble: #' #' * `distribution` : Distribution which was specified in [ml_estimation]. #' * `bounds` : Specified bound(s). #' * `direction` : Specified direction. #' * `model_estimation` : Input list with classes `wt_model` and `wt_ml_estimation`. #' #' @encoding UTF-8 #' #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' ## Data for two-parametric model: #' data_2p <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' ## Data for three-parametric model: #' data_3p <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Model estimation with ml_estimation(): #' ml_2p <- ml_estimation( #' data_2p, #' distribution = "weibull" #' ) #' #' ml_3p <- ml_estimation( #' data_3p, #' distribution = "lognormal3", #' conf_level = 0.90 #' ) #' #' #' # Example 1 - Two-sided 95% confidence interval for probabilities ('y'): #' conf_fisher_1 <- confint_fisher( #' x = ml_2p, #' bounds = "two_sided", #' conf_level = 0.95, #' direction = "y" #' ) #' #' # Example 2 - One-sided lower/upper 90% confidence interval for quantiles ('x'): #' conf_fisher_2_1 <- confint_fisher( #' x = ml_2p, #' bounds = "lower", #' conf_level = 0.90, #' direction = "x" #' ) #' #' conf_fisher_2_2 <- confint_fisher( #' x = ml_2p, #' bounds = "upper", #' conf_level = 0.90, #' direction = "x" #' ) #' #' # Example 3 - Two-sided 90% confidence intervals for both directions using #' # a three-parametric model: #' #' conf_fisher_3_1 <- confint_fisher( #' x = ml_3p, #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "y" #' ) #' #' conf_fisher_3_2 <- confint_fisher( #' x = ml_3p, #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "x" #' ) #' #' @md #' #' @export confint_fisher <- function(x, ...) { UseMethod("confint_fisher") } #' @rdname confint_fisher #' #' @export confint_fisher.wt_model <- function(x, b_lives = c(0.01, 0.1, 0.50), bounds = c( "two_sided", "lower", "upper" ), conf_level = 0.95, direction = c("y", "x"), ... ) { stopifnot(inherits(x, "wt_ml_estimation")) NextMethod() } #' @export confint_fisher.wt_ml_estimation <- function(x, b_lives = c(0.01, 0.1, 0.50), bounds = c( "two_sided", "lower", "upper" ), conf_level = 0.95, direction = c("y", "x"), ... ) { bounds <- match.arg(bounds) direction <- match.arg(direction) confint_fisher_( model_estimation = x, b_lives = b_lives, bounds = bounds, conf_level = conf_level, direction = direction ) } #' Fisher's Confidence Bounds for Quantiles and Probabilities #' #' @inherit confint_fisher description details references #' #' @inheritParams delta_method #' @inheritParams confint_betabinom.default #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, e.g. #' operating time (days/months in service), mileage (km, miles), load cycles. #' @param direction A character string specifying the direction of the confidence #' interval. `"y"` for failure probabilities or `"x"` for quantiles. #' #' @template return-fisher-confidence-intervals #' @return #' Further information is stored in the attributes of this tibble: #' #' * `distribution` : Distribution which was specified in [ml_estimation]. #' * `bounds` : Specified bound(s). #' * `direction` : Specified direction. #' #' @seealso [confint_fisher] #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' status_1 <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' #' cycles <- alloy$cycles #' status_2 <- alloy$status #' #' #' # Model estimation with ml_estimation(): #' ml <- ml_estimation( #' x = obs, #' status = status_1, #' distribution = "weibull", #' conf_level = 0.90 #' ) #' #' ml_2 <- ml_estimation( #' x = cycles, #' status = status_2, #' distribution = "lognormal3" #' ) #' #' # Example 1 - Two-sided 95% confidence interval for probabilities ('y'): #' conf_fisher_1 <- confint_fisher( #' x = obs, #' status = status_1, #' dist_params = ml$coefficients, #' dist_varcov = ml$varcov, #' distribution = "weibull", #' bounds = "two_sided", #' conf_level = 0.95, #' direction = "y" #' ) #' #' # Example 2 - One-sided lower/upper 90% confidence interval for quantiles ('x'): #' conf_fisher_2_1 <- confint_fisher( #' x = obs, #' status = status_1, #' dist_params = ml$coefficients, #' dist_varcov = ml$varcov, #' distribution = "weibull", #' bounds = "lower", #' conf_level = 0.90, #' direction = "x" #' ) #' #' conf_fisher_2_2 <- confint_fisher( #' x = obs, #' status = status_1, #' dist_params = ml$coefficients, #' dist_varcov = ml$varcov, #' distribution = "weibull", #' bounds = "upper", #' conf_level = 0.90, #' direction = "x" #' ) #' #' # Example 3 - Two-sided 90% confidence intervals for both directions using #' # a three-parametric model: #' #' conf_fisher_3_1 <- confint_fisher( #' x = cycles, #' status = status_2, #' dist_params = ml_2$coefficients, #' dist_varcov = ml_2$varcov, #' distribution = "lognormal3", #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "y" #' ) #' #' conf_fisher_3_2 <- confint_fisher( #' x = cycles, #' status = status_2, #' dist_params = ml_2$coefficients, #' dist_varcov = ml_2$varcov, #' distribution = "lognormal3", #' bounds = "two_sided", #' conf_level = 0.90, #' direction = "x" #' ) #' #' @md #' #' @export confint_fisher.default <- function(x, status, dist_params, dist_varcov, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), b_lives = c(0.01, 0.1, 0.50), bounds = c("two_sided", "lower", "upper"), conf_level = 0.95, direction = c("y", "x"), ... ) { bounds <- match.arg(bounds) direction <- match.arg(direction) distribution <- match.arg(distribution) # Fake model_estimation model_estimation <- list( data = tibble::tibble( x = x, status = status, cdf_estimation_method = NA_character_ ), coefficients = dist_params, varcov = dist_varcov, distribution = distribution ) confint_fisher_( model_estimation = model_estimation, b_lives = b_lives, bounds = bounds, conf_level = conf_level, direction = direction ) } confint_fisher_ <- function(model_estimation, b_lives, bounds, conf_level, direction ) { # Prepare function inputs: x <- model_estimation$data$x status <- model_estimation$data$status dist_params <- model_estimation$coefficients dist_varcov <- model_estimation$varcov distribution <- model_estimation$distribution n <- length(x) ## Only range of failed units is considered: x_ob <- x[status == 1] # Step 1: Determine x-y ranges and add the appropriate B_p-lives: x_y_b_lives <- add_b_lives(x_ob, dist_params, distribution, b_lives) x_seq <- x_y_b_lives$x_seq y_seq <- x_y_b_lives$y_seq # Step 2: Normal approx. confidence intervals w.r.t 'direction' and 'bounds': ## Quantiles of normal distribution for chosen bounds (two-sided or one-sided): q_n <- switch( bounds, "two_sided" = stats::qnorm((1 + conf_level) / 2), stats::qnorm(conf_level) ) ## Confidence intervals for direction = "x": if (direction == "x") { se_delta <- delta_method( x = y_seq, dist_params = dist_params, dist_varcov = dist_varcov, distribution = distribution, direction = direction ) ## Ensure that confidence intervals are strictly positive: w <- exp((q_n * se_delta) / x_seq) w <- switch( bounds, "two_sided" = list(lower_bound = 1 / w, upper_bound = w), "lower" = list(lower_bound = 1 / w), "upper" = list(upper_bound = w) ) list_confint <- purrr::map(w, `*`, x_seq) names(list_confint) <- names(w) } else { ## Confidence intervals for direction = "y": se_delta <- delta_method( x = x_seq, dist_params = dist_params, dist_varcov = dist_varcov, distribution = distribution, direction = direction ) w <- q_n * se_delta ## Standardized random variable: z <- standardize( x = x_seq, dist_params = dist_params, distribution = distribution ) zw <- switch( bounds, "two_sided" = list(lower_bound = z - w, upper_bound = z + w), "lower" = list(lower_bound = z - w), "upper" = list(upper_bound = z + w) ) ## Model-specific standard distribution: pfun <- switch( std_parametric(distribution), "sev" = , "weibull" = psev, "normal" = , "lognormal" = stats::pnorm, "logistic" = , "loglogistic" = stats::plogis, "exponential" = stats::pexp ) list_confint <- purrr::map(zw, pfun) names(list_confint) <- names(zw) } # Step 3: Form output: list_output <- c( list(x = x_seq, prob = y_seq, std_err = se_delta), list_confint ) tbl_out <- tibble::as_tibble(list_output) ## Add cdf_estimation_method (same colnames as confint_betabinom's output): tbl_out$cdf_estimation_method <- NA_character_ tbl_out <- structure( tbl_out, distribution = distribution, bounds = bounds, direction = direction ) ## Only add model_estimation if not faked by .default: if (inherits(model_estimation, "wt_model_estimation")) { attr(tbl_out, "model_estimation") <- model_estimation } # Make output usable for generics class(tbl_out) <- c("wt_confint", class(tbl_out)) tbl_out }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/confidence_intervals.R
# Function that adds B_p-lives for p's covered by the range of probabilities: add_b_lives <- function(x, dist_params, distribution, b_lives ) { # Range of failed items: x_min <- min(x, na.rm = TRUE) x_max <- max(x, na.rm = TRUE) x_seq <- seq(x_min, x_max, length.out = 100) # Range of probabilities calculated with estimated regression line: y_seq <- predict_prob(q = x_seq, dist_params = dist_params, distribution = distribution) # Looking for B_p-lives in range of estimated ones: b_lives_present <- b_lives[b_lives >= y_seq[1] & b_lives <= y_seq[length(y_seq)]] # Add them: y_seq <- sort(unique(c(y_seq, b_lives_present))) x_seq <- predict_quantile( p = y_seq, dist_params = dist_params, distribution = distribution ) list( x_seq = x_seq, y_seq = y_seq ) } # BB Bounds for probabilities (direction = "y"): conf_bb_y <- function(y, # sequence of probabilities returned by 'add_b_lives()'. n, # sample size of all units (n_f + n_s). r, # interpolated ranks computed with Benards formula. bounds, conf_level ) { r_inv <- n - r + 1 # Confidence intervals: p_conf <- switch( bounds, "two_sided" = c(lower_bound = (1 - conf_level), upper_bound = (1 + conf_level)) / 2, "lower" = c(lower_bound = 1 - conf_level), "upper" = c(upper_bound = conf_level) ) list_confint <- purrr::map( p_conf, stats::qbeta, shape1 = r, shape2 = r_inv ) names(list_confint) <- names(p_conf) list_confint }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/confidence_intervals_helpers.R
#' Fatigue Life for Alloy T7989 Specimens #' #' A dataset containing the number of cycles of fatigue life for Alloy T7987 #' specimens. #' #' @format A tibble with 72 rows and 2 variables: #' \describe{ #' \item{cycles}{Number of cycles (in thousands).} #' \item{status}{If specimen failed before 300 thousand cycles \code{1} else \code{0}.} #' } #' #' @source Meeker, William Q; Escobar, Luis A., Statistical Methods for #' Reliability Data, New York: Wiley series in probability and statistics #' (1998, p.131) "alloy" #' Distance to Failure for Vehicle Shock Absorbers #' #' Distance to failure for 38 vehicle shock absorbers. #' #' @format A tibble with 38 rows and 3 variables: #' \describe{ #' \item{distance}{Observed distance.} #' \item{failure_mode}{ #' One of two failure modes (\code{mode_1} and \code{mode_2}) #' or \code{censored} if no failure occurred. #' } #' \item{status}{ #' If \code{failure_mode} is either \code{mode_1} or \code{mode_2} #' this is \code{1} else \code{0}. #' } #' } #' #' @source Meeker, William Q; Escobar, Luis A., Statistical Methods for #' Reliability Data, New York: Wiley series in probability and statistics #' (1998, p.630) "shock" #' High Voltage Stress Test for the Dielectric Insulation of Generator armature bars #' #' A sample of 58 segments of bars were subjected to a high voltage stress test. #' Two failure modes occurred, Mode D (degradation failure) and Mode E (early failure). #' #' @format A tibble with 58 rows and 3 variables: #' \describe{ #' \item{hours}{Observed hours.} #' \item{failure_mode}{ #' One of two failure modes (\code{D} and \code{E}) #' or \code{censored} if no failure occurred. #' } #' \item{status}{ #' If \code{failure_mode} is either \code{D} or \code{E} #' this is \code{1} else \code{0}. #' } #' } #' #' @source Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by #' Failure Mode, Quality Progress, 35(6), 47-52, 2002 "voltage" #' Field Data #' #' @description #' An illustrative field dataset that contains a variety of variables commonly #' collected in the automotive sector. #' #' The dataset has complete information about failed and incomplete information #' about intact vehicles. See 'Format' and 'Details' for further insights. #' #' @details #' All vehicles were produced in 2014 and an analysis of the field data was #' made at the end of 2015. At the date of analysis, there were 684 failed and #' 10,000 intact vehicles. #' #' \strong{Censored vehicles}: #' #' For censored units the service time (\code{dis}) was computed as the difference #' of the date of analysis \code{"2015-12-31"} and the \code{registration_date}. #' #' For many units the latter date is unknown. For these, the difference of the #' analysis date and \code{production_date} was used to get a rough estimation of #' the real service time. This uncertainty has to be considered in the subsequent #' analysis (see \strong{delay in registration} in the section 'Details' of #' \code{\link{mcs_delay}}). #' #' Furthermore, due to the delay in report, the computed service time could also #' be inaccurate. This uncertainty should be considered as well (see #' \strong{delay in report} in the section 'Details' of \code{\link{mcs_delay}}). #' #' The lifetime characteristic \code{mileage} is unknown for all censored units. #' If an analysis is to be made for this lifetime characteristic, covered distances #' for these units have to be estimated (see \code{\link{mcs_mileage}}). #' #' \strong{Failed vehicles}: #' For failed units the service time (\code{dis}) is computed as the difference #' of \code{repair_date} and \code{registration_date}, which are known for all of them. #' #' @format A tibble with 10,684 rows and 20 variables: #' \describe{ #' \item{vin}{Vehicle identification number.} #' \item{dis}{Days in service.} #' \item{mileage}{Distances covered, which are unknown for censored units.} #' \item{status}{\code{1} for failed and \code{0} for censored units.} #' \item{production_date}{Date of production.} #' \item{registration_date}{Date of registration. Known for all failed units and #' for a few intact units.} #' \item{repair_date}{The date on which the failure was repaired. It is assumed #' that the repair date is equal to the date of failure occurrence.} #' \item{report_date}{The date on which lifetime information about the failure #' were available.} #' \item{country}{Delivering country.} #' \item{region}{The region within the country of delivery. Known for registered #' vehicles, \code{NA} for units with a missing \code{registration_date}.} #' \item{climatic_zone}{Climatic zone based on "Köppen-Geiger" climate classification. #' Known for registered vehicles, \code{NA} for units with a missing \code{registration_date}.} #' \item{climatic_subzone}{Climatic subzone based on "Köppen-Geiger" climate classification. #' Known for registered vehicles, \code{NA} for units with a \code{registration_date}.} #' \item{brand}{Brand of the vehicle.} #' \item{vehicle_model}{Model of the vehicle.} #' \item{engine_type}{Type of the engine.} #' \item{engine_date}{Date where the engine was installed.} #' \item{gear_type}{Type of the gear.} #' \item{gear_date}{Date where the gear was installed.} #' \item{transmission}{Transmission of the vehicle.} #' \item{fuel}{Vehicle fuel.} #' } #' #' @seealso \code{\link{mcs_mileage_data}} #' "field_data"
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/data.R
#' Parameter Estimation of a Delay Distribution #' #' @description #' This function models a delay (in days) random variable (e.g. in logistic, #' registration, report) using a supposed continuous distribution. First, the #' row-wise differences in days of the related date columns are calculated and then #' the parameter(s) of the assumed distribution is (are) estimated with maximum #' likelihood. See 'Details' for more information. #' #' @details #' The distribution parameter(s) is (are) determined on the basis of complete #' cases, i.e. there is no `NA` (row-wise) in one of the related date columns. #' Time differences less than or equal to zero are not considered as well. #' #' @param x A `tibble` with class `wt_mcs_delay_data` returned by [mcs_delay_data]. #' @param distribution Supposed distribution of the respective delay. #' @template dots #' #' @return A list with class `wt_delay_estimation` which contains: #' #' * `coefficients` : A named vector of estimated parameter(s). #' * `delay` : A numeric vector of element-wise computed differences in days. #' * `distribution` : Specified distribution. #' #' If more than one delay was considered in [mcs_delay_data], the resulting output #' is a list with class `wt_delay_estimation_list`. In this case each list element #' has class `wt_delay_estimation` and the items listed above, are included. #' #' @examples #' # MCS data preparation: #' ## Data for delay in registration: #' mcs_tbl_1 <- mcs_delay_data( #' field_data, #' date_1 = production_date, #' date_2 = registration_date, #' time = dis, #' status = status, #' id = vin #' ) #' #' ## Data for delay in report: #' mcs_tbl_2 <- mcs_delay_data( #' field_data, #' date_1 = repair_date, #' date_2 = report_date, #' time = dis, #' status = status, #' id = vin #' ) #' #' ## Data for both delays: #' mcs_tbl_both <- mcs_delay_data( #' field_data, #' date_1 = c(production_date, repair_date), #' date_2 = c(registration_date, report_date), #' time = dis, #' status = status, #' id = vin #' ) #' #' # Example 1 - Delay in registration: #' params_delay_regist <- dist_delay( #' x = mcs_tbl_1, #' distribution = "lognormal" #' ) #' #' # Example 2 - Delay in report: #' params_delay_report <- dist_delay( #' x = mcs_tbl_2, #' distribution = "exponential" #' ) #' #' # Example 3 - Delays in registration and report with same distribution: #' params_delays <- dist_delay( #' x = mcs_tbl_both, #' distribution = "lognormal" #' ) #' #' # Example 4 - Delays in registration and report with different distributions: #' params_delays_2 <- dist_delay( #' x = mcs_tbl_both, #' distribution = c("lognormal", "exponential") #' ) #' #' @md #' #' @export dist_delay <- function(...) { UseMethod("dist_delay") } #' @rdname dist_delay #' #' @export dist_delay.wt_mcs_delay_data <- function( ..., x, distribution = c("lognormal", "exponential") ) { # Check that '...' argument is not used: check_dots(...) # Extract 'mcs_start_dates' and 'mcs_end_dates' columns as list: date_1_names <- attr(x, "mcs_start_dates") date_2_names <- attr(x, "mcs_end_dates") date_1 <- dplyr::select(x, {{date_1_names}}) date_2 <- dplyr::select(x, {{date_2_names}}) # Use default method: dist_delay.default( date_1 = date_1, date_2 = date_2, distribution = distribution ) } #' Parameter Estimation of a Delay Distribution #' #' @description #' This function models a delay (in days) random variable (e.g. in logistic, #' registration, report) using a supposed continuous distribution. First, the #' element-wise differences in days of both vectors `date_1` and `date_2` are #' calculated and then the parameter(s) of the assumed #' distribution is (are) estimated with maximum likelihood. See 'Details' for #' more information. #' #' @details #' The distribution parameter(s) is (are) determined on the basis of complete #' cases, i.e. there is no `NA` in one of the related vector elements #' `c(date_1[i], date_2[i])`. Time differences less than or equal to zero are #' not considered as well. #' #' @param date_1 A vector of class `character` or `Date`, in the format "yyyy-mm-dd", #' representing the earlier of the two dates belonging to a particular delay. #' Use `NA` for missing elements. #' #' If more than one delay is to be considered, use a list where the first element #' is the earlier date of the first delay, the second element is the earlier date #' of the second delay, and so forth (see 'Examples'). #' @param date_2 A vector of class `character` or `Date` in the format "yyyy-mm-dd". #' `date_2` is the counterpart of `date_1` and is used the same as `date_1`, just with #' the later date(s) of the particular delay(s). Use `NA` for missing elements. #' @inheritParams dist_delay #' #' @return A list with class `wt_delay_estimation` which contains: #' #' * `coefficients` : A named vector of estimated parameter(s). #' * `delay` : A numeric vector of element-wise computed differences in days. #' * `distribution` : Specified distribution. #' #' If more than one delay was considered, the resulting output is a list with class #' `wt_delay_estimation_list`. In this case each list element has class #' `wt_delay_estimation` and the items listed above, are included. #' #' @seealso [dist_delay] #' #' @examples #' # Example 1 - Delay in registration: #' params_delay_regist <- dist_delay( #' date_1 = field_data$production_date, #' date_2 = field_data$registration_date, #' distribution = "lognormal" #' ) #' #' # Example 2 - Delay in report: #' params_delay_report <- dist_delay( #' date_1 = field_data$repair_date, #' date_2 = field_data$report_date, #' distribution = "exponential" #' ) #' #' # Example 3 - Delays in registration and report with same distribution: #' params_delays <- dist_delay( #' date_1 = list(field_data$production_date, field_data$repair_date), #' date_2 = list(field_data$registration_date, field_data$report_date), #' distribution = "lognormal" #' ) #' #' # Example 4 - Delays in registration and report with different distributions: #' params_delays_2 <- dist_delay( #' date_1 = list(field_data$production_date, field_data$repair_date), #' date_2 = list(field_data$registration_date, field_data$report_date), #' distribution = c("lognormal", "exponential") #' ) #' #' @md #' #' @export dist_delay.default <- function(..., date_1, date_2, distribution = c("lognormal", "exponential") ) { # Check that '...' argument is not used: check_dots(...) # Convert date_1 and date_2 to lists if they are vectors: if (!is.list(date_1)) date_1 <- list(date_1) if (!is.list(date_2)) date_2 <- list(date_2) # Default for distribution if not specified: if (missing(distribution)) { distribution <- "lognormal" } # Checks: ## Check for (multiple) distributions: distribution <- match.arg(distribution, several.ok = TRUE) ## Compare length of date_1 and distribution: if (!(length(distribution) == length(date_1) || length(distribution) == 1L)) { stop( "'distribution' must be either length one or 'length(date_1)'", call. = FALSE ) } ## Check for different length in date_1 and date_2: if (length(unique(lengths(c(date_1, date_2)))) != 1L) { stop( "All elements of 'date_1' and 'date_2' must have the same length!", call. = FALSE ) } # Do dist_delay_() with respect to the number of delays: if (length(date_1) == 1L) { ## One delay is to be considered: ### unlist kills class "Date" -> purrr::reduce(., "c") dist_estimation_list <- dist_delay_( purrr::reduce(date_1, "c"), purrr::reduce(date_2, "c"), distribution = distribution ) } else { ## Multiple delays are to be considered: ### map over dates and distribution(s): dist_estimation_list <- purrr::pmap( list( date_1, date_2, distribution ), dist_delay_ ) # Prepare output with respect to multiple delays: names(dist_estimation_list) <- paste0("delay_", seq_along(dist_estimation_list)) class(dist_estimation_list) <- c("wt_delay_estimation_list", class(dist_estimation_list)) } dist_estimation_list } # Helper function that performs the estimation of a parametric delay distribution: dist_delay_ <- function(date_1, date_2, distribution = c("lognormal", "exponential") ) { # Defining delay variable (for estimation) and origin variable (output): t_delay <- t_delay_origin <- as.numeric( difftime( time1 = as.Date(date_2, format = "%Y-%m-%d"), time2 = as.Date(date_1, format = "%Y-%m-%d"), units = "days" ) ) # Checks: ## all NA: if (all(is.na(t_delay))) { stop( "All date differences are 'NA'. No parameters can be estimated!", call. = FALSE ) } ## any or all delays are less than or equal to zero: if (any(t_delay <= 0, na.rm = TRUE)) { if (all(t_delay <= 0, na.rm = TRUE)) { ### all: stop( "All date differences are less than or equal to 0. ", "No parameters can be estimated!", call. = FALSE ) } else { ### any: warning( "At least one of the date differences is less than or equal to 0 and ", "is ignored for the estimation step!", call. = FALSE ) t_delay <- t_delay[t_delay > 0] } } if (distribution == "lognormal") { # sample size used for the computation of the population standard deviation. n <- sum(!is.na(t_delay)) ml_loc <- mean(log(t_delay), na.rm = TRUE) ml_sc <- stats::sd(log(t_delay), na.rm = TRUE) * (n - 1) / n estimates <- c(loc = ml_loc, sc = ml_sc) } if (distribution == "exponential") { ml_sc <- mean(t_delay, na.rm = TRUE) estimates <- c(sc = ml_sc) } dist_output <- list( coefficients = estimates, delay = t_delay_origin, distribution = distribution ) class(dist_output) <- c("wt_delay_estimation", class(dist_output)) return(dist_output) } #' @export print.wt_delay_estimation <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat("Coefficients:\n") print(format(stats::coef(x), digits = digits), print.gap = 2L, quote = FALSE) invisible(x) } #' @export print.wt_delay_estimation_list <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat(paste("List of", length(x), "delay estimations:\n")) cat("\n") purrr::walk2(x, seq_along(x), function(x, y) { cat(paste0("Delay distribution ", y, ": ", "'", x$distribution, "'", "\n")) print(x) cat("\n") }) invisible(x) } #' Parameter Estimation of the Delay in Registration Distribution #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `dist_delay_register()` is no longer under active development, switching to #' [dist_delay] is recommended. #' #' @details #' This function introduces a delay random variable by calculating the time #' difference between the registration and production date for the sample units #' and afterwards estimates the parameter(s) of a supposed distribution, #' using maximum likelihood. #' #' @param date_prod A vector of class `character` or `Date`, in the #' format "yyyy-mm-dd", indicating the date of production of a unit. #' Use `NA` for missing elements. #' @param date_register A vector of class `character` or `Date`, in #' the format "yyyy-mm-dd", indicating the date of registration of a unit. #' Use `NA` for missing elements. #' @param distribution Supposed distribution of the random variable. Only #' `"lognormal"`is implemented. #' #' @return A named vector of estimated parameters for the specified #' distribution. #' #' @examples #' date_of_production <- c("2014-07-28", "2014-02-17", "2014-07-14", #' "2014-06-26", "2014-03-10", "2014-05-14", #' "2014-05-06", "2014-03-07", "2014-03-09", #' "2014-04-13", "2014-05-20", "2014-07-07", #' "2014-01-27", "2014-01-30", "2014-03-17", #' "2014-02-09", "2014-04-14", "2014-04-20", #' "2014-03-13", "2014-02-23", "2014-04-03", #' "2014-01-08", "2014-01-08") #' date_of_registration <- c(NA, "2014-03-29", "2014-12-06", "2014-09-09", #' NA, NA, "2014-06-16", NA, "2014-05-23", #' "2014-05-09", "2014-05-31", NA, "2014-04-13", #' NA, NA, "2014-03-12", NA, "2014-06-02", #' NA, "2014-03-21", "2014-06-19", NA, NA) #' #' params_delay_regist <- dist_delay_register( #' date_prod = date_of_production, #' date_register = date_of_registration, #' distribution = "lognormal" #' ) #' #' @md #' #' @export dist_delay_register <- function(date_prod, date_register, distribution = "lognormal" ) { deprecate_soft("2.0.0", "dist_delay_register()", "dist_delay()") distribution <- match.arg(distribution) # delay variable: t_regist <- as.numeric( difftime( time1 = as.Date(date_register, format = "%Y-%m-%d"), time2 = as.Date(date_prod, format = "%Y-%m-%d"), units = "days" ) ) # test for delays: all NA and less than or equal to 0. # all NA: if (all(is.na(t_regist))) { stop( "All differences are NA. No parameters can be estimated!", call. = FALSE ) } # all less than or equal to zero: if (all(t_regist <= 0, na.rm = TRUE)) { stop( "All differences are less than or equal to 0. No parameters can be ", "estimated!", call. = FALSE ) } # any less than or equal to zero: if (!all(t_regist <= 0, na.rm = TRUE) && any(t_regist <= 0, na.rm = TRUE)) { warning( "At least one of the time differences is less than or equal to 0 and is", " ignored for the estimation step!", call. = FALSE ) t_regist <- t_regist[t_regist > 0] } # sample size used for the computation of the population standard deviation. n <- length(!is.na(t_regist)) ml_loc <- mean(log(t_regist), na.rm = TRUE) ml_sc <- stats::sd(log(t_regist), na.rm = TRUE) * (n - 1) / n estimates <- c(loc = ml_loc, sc = ml_sc) return(estimates) } #' Parameter Estimation of the Delay in Report Distribution #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `dist_delay_report()`is no longer under active development, switching to #' [dist_delay] is recommended. #' #' @details #' This function introduces a delay random variable by calculating the time #' difference between the report and repair date for the sample units #' and afterwards estimates the parameter(s) of a supposed distribution, #' using maximum likelihood. #' #' @inheritParams dist_delay_register #' #' @param date_repair a vector of class `character` or `Date`, in the #' format "yyyy-mm-dd", indicating the date of repair of a failed unit. #' Use `NA` for missing elements. #' @param date_report a vector of class `character` or `Date`, in the #' format "yyyy-mm-dd", indicating the date of report of a failed unit. #' Use `NA` for missing elements. #' #' @return A named vector of estimated parameters for the specified #' distribution. #' #' @examples #' date_of_repair <- c(NA, "2014-09-15", "2015-07-04", "2015-04-10", NA, #' NA, "2015-04-24", NA, "2015-04-25", "2015-04-24", #' "2015-06-12", NA, "2015-05-04", NA, NA, #' "2015-05-22", NA, "2015-09-17", NA, "2015-08-15", #' "2015-11-26", NA, NA) #' #' date_of_report <- c(NA, "2014-10-09", "2015-08-28", "2015-04-15", NA, #' NA, "2015-05-16", NA, "2015-05-28", "2015-05-15", #' "2015-07-11", NA, "2015-08-14", NA, NA, #' "2015-06-05", NA, "2015-10-17", NA, "2015-08-21", #' "2015-12-02", NA, NA) #' #' params_delay_report <- dist_delay_report( #' date_repair = date_of_repair, #' date_report = date_of_report, #' distribution = "lognormal" #' ) #' #' @md #' #' @export dist_delay_report <- function(date_repair, date_report, distribution = "lognormal" ) { deprecate_soft("2.0.0", "dist_delay_report()", "dist_delay()") distribution <- match.arg(distribution) # delay variable: t_report <- as.numeric( difftime( time1 = as.Date(date_report, format = "%Y-%m-%d"), time2 = as.Date(date_repair, format = "%Y-%m-%d"), units = "days" ) ) # test for delays: all NA and less than or equal to 0. # all NA: if (all(is.na(t_report))) { stop( "All differences are NA. No parameters can be estimated!", call. = FALSE ) } # all less than or equal to zero: if (all(t_report <= 0, na.rm = TRUE)) { stop( "All differences are less than or equal to 0. No parameters can be ", "estimated!", call. = FALSE ) } # any less than or equal to zero: if (!all(t_report <= 0, na.rm = TRUE) && any(t_report <= 0, na.rm = TRUE)) { warning( "At least one of the time differences is less than or equal to 0 and is", " ignored for the estimation step!", call. = FALSE ) t_report <- t_report[t_report > 0] } # sample size used for the computation of the population standard deviation. n <- length(!is.na(t_report)) ml_loc <- mean(log(t_report), na.rm = TRUE) ml_sc <- stats::sd(log(t_report), na.rm = TRUE) * (n - 1) / n estimates <- c(loc = ml_loc, sc = ml_sc) return(estimates) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/delay_distributions.R
#' Delta Method for Parametric Lifetime Distributions #' #' @description #' This function applies the *delta method* to a parametric lifetime distribution. #' #' @details #' The delta method estimates the standard errors for quantities that can be #' written as non-linear functions of ML estimators. Hence, the parameters as #' well as the variance-covariance matrix of these quantities have to be estimated #' with [maximum likelihood][ml_estimation]. #' #' The estimated standard errors are used to calculate Fisher's (normal #' approximation) confidence intervals. For confidence bounds on the probability, #' standard errors of the standardized quantiles (`direction = "y"`) have to be #' computed (*z-procedure*) and for bounds on quantiles, standard errors of #' quantiles (`direction = "x"`) are required. For more information see #' [confint_fisher]. #' #' @param x A numeric vector of probabilities or quantiles. If the standard errors #' of quantiles should be determined the corresponding probabilities have to be #' specified, and if the standard errors of standardized quantiles (z-values) #' should be computed corresponding quantiles are required. #' @param dist_params The parameters (`coefficients`) returned by [ml_estimation]. #' @param dist_varcov The variance-covariance-matrix (`varcov`) returned by #' [ml_estimation]. #' @param distribution Supposed distribution of the random variable. Has to be in #' line with the specification made in [ml_estimation]. #' @param direction A character string specifying for which quantity the standard #' errors are calculated. `"y"` if `x` are quantiles or `"x"` if `x` are probabilities. #' @param p `r lifecycle::badge("soft-deprecated")`: Use `x` instead. #' #' @return A numeric vector of estimated standard errors for quantiles or #' standardized quantiles (*z-values*). #' #' @encoding UTF-8 #' #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' data <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' # Parameter estimation using maximum likelihood: #' mle <- ml_estimation( #' data, #' distribution = "weibull", #' conf_level = 0.95 #' ) #' #' # Example 1 - Standard errors of standardized quantiles: #' delta_y <- delta_method( #' x = shock$distance, #' dist_params = mle$coefficients, #' dist_varcov = mle$varcov, #' distribution = "weibull", #' direction = "y" #' ) #' #' # Example 2 - Standard errors of quantiles: #' delta_x <- delta_method( #' x = seq(0.01, 0.99, 0.01), #' dist_params = mle$coefficients, #' dist_varcov = mle$varcov, #' distribution = "weibull", #' direction = "x" #' ) #' #' @md #' #' @export delta_method <- function(x, dist_params, dist_varcov, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), direction = c("y", "x"), p = deprecated() ) { if (lifecycle::is_present(p)) { deprecate_warn("2.1.0", "delta_method(p)", "delta_method(x)") x <- p } # Checks: direction <- match.arg(direction) distribution <- match.arg(distribution) check_dist_params(dist_params, distribution) dm_vectorized <- Vectorize(delta_method_, "x") dm_vectorized( x = x, dist_params = dist_params, dist_varcov = dist_varcov, distribution = distribution, direction = direction ) } delta_method_ <- function(x, dist_params, dist_varcov, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), direction = c("y", "x") ) { n_par <- length(dist_params) # Only consider parameters of standard distribution: if (has_thres(distribution)) { n_par <- n_par - 1L } # Standard Errors for quantiles: if (direction == "x") { ## Step 1: Determine first derivatives of the quantile function t_p: ### Outer derivative is often the quantile function: q <- predict_quantile( p = x, dist_params = dist_params[1:n_par], distribution = std_parametric(distribution) ) ### Inner derivative is often the standardized quantile function: z <- standardize( x = q, dist_params = dist_params[1:n_par], distribution = std_parametric(distribution) ) ### Derivatives of scale or location-scale distributions: dt_dmu <- if (std_parametric(distribution) != "exponential") 1 else NULL dt_dsc <- z dpar <- c(dt_dmu, dt_dsc) ### Derivatives of (log-)location-scale distributions: if (std_parametric(distribution) %in% c("weibull", "lognormal", "loglogistic")) { dpar <- dpar * q } ### Derivative w.r.t threshold: if (has_thres(distribution)) { dpar <- c(dpar, 1) } # Standard Errors for z using the "z-Procedure": } else { # Standardized Random Variable: z <- standardize(x, dist_params = dist_params, distribution = distribution) ## Step 1: Determine first derivatives of the standardized quantile z: ### Derivative w.r.t scale or location-scale: dz_dmu <- if (distribution != "exponential") (-1 / dist_params[n_par]) else NULL dz_dsc <- (-1 / dist_params[n_par]) * z dpar <- c(dz_dmu, dz_dsc) ### Derivative w.r.t threshold: if (has_thres(distribution)) { if (distribution == "exponential2") { dpar <- rev(dpar) } else { dz_dgam <- (1 / dist_params[n_par]) * (1 / (dist_params[n_par + 1] - x)) dpar <- c(dpar, dz_dgam) } } } ## Step 2: Determine variance and standard errors: dvar <- t(dpar) %*% dist_varcov %*% dpar std_err <- sqrt(dvar) std_err }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/delta_method.R
#' Log-Likelihood Function for Parametric Lifetime Distributions #' #' @description #' This function computes the log-likelihood value with respect to a given set #' of parameters. In terms of *Maximum Likelihood Estimation* this function can #' be optimized ([optim][stats::optim]) to estimate the parameters and #' variance-covariance matrix of the parameters. #' #' @inheritParams ml_estimation #' @inheritParams predict_quantile #' #' @return #' Returns the log-likelihood value for the parameters in `dist_params` given #' the data. #' #' @encoding UTF-8 #' #' @template dist-params #' #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' data <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Example 1 - Evaluating Log-Likelihood function of two-parametric weibull: #' loglik_weib <- loglik_function( #' x = data, #' dist_params = c(5.29, 0.33), #' distribution = "weibull" #' ) #' #' # Example 2 - Evaluating Log-Likelihood function of three-parametric weibull: #' loglik_weib3 <- loglik_function( #' x = data, #' dist_params = c(4.54, 0.76, 92.99), #' distribution = "weibull3" #' ) #' #' @md #' #' @export loglik_function <- function(x, ...) { UseMethod("loglik_function") } #' @rdname loglik_function #' #' @export loglik_function.wt_reliability_data <- function( x, wts = rep(1, nrow(x)), dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), ... ) { # Call `loglik_function.default()`: loglik_function.default( x = x$x, status = x$status, wts = wts, dist_params = dist_params, distribution = distribution ) } #' Log-Likelihood Function for Parametric Lifetime Distributions #' #' @inherit loglik_function description return references #' #' @inheritParams ml_estimation.default #' @inheritParams predict_quantile #' #' @encoding UTF-8 #' #' @template dist-params #' #' @seealso [loglik_function] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Example 1 - Evaluating Log-Likelihood function of two-parametric weibull: #' loglik_weib <- loglik_function( #' x = cycles, #' status = status, #' dist_params = c(5.29, 0.33), #' distribution = "weibull" #' ) #' #' # Example 2 - Evaluating Log-Likelihood function of three-parametric weibull: #' loglik_weib3 <- loglik_function( #' x = cycles, #' status = status, #' dist_params = c(4.54, 0.76, 92.99), #' distribution = "weibull3" #' ) #' #' @md #' #' @export loglik_function.default <- function(x, status, wts = rep(1, length(x)), dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), ... ) { distribution <- match.arg(distribution) check_dist_params(dist_params, distribution) loglik_function_( x = x, status = status, wts = wts, dist_params = dist_params, distribution = distribution ) } # Helper function for log-likelihood calculation: loglik_function_ <- function(x, status, wts, dist_params, distribution, log_scale = FALSE ) { d <- status if (std_parametric(distribution) == "exponential") { mu <- NULL sig <- dist_params[1] thres <- dist_params[2] } else { mu <- dist_params[1] sig <- dist_params[2] thres <- dist_params[3] } if (log_scale) sig <- exp(sig) # Threshold model: if (!is.na(thres)) { x <- x - thres ## Restriction of threshold models, i.e. x > threshold parameter: subs <- x > 0 x <- x[subs] d <- d[subs] wts <- wts[subs] } # Use distribution without threshold: distribution <- std_parametric(distribution) ## Standardize x: z <- standardize(x = x, dist_params = c(mu, sig), distribution = distribution) ## Switch between distributions: switch(distribution, "weibull" = ds <- dsev(z) / (sig * x), "lognormal" = ds <- stats::dnorm(z) / (sig * x), "loglogistic" = ds <- stats::dlogis(z) / (sig * x), "sev" = ds <- dsev(z) / sig, "normal" = ds <- stats::dnorm(z) / sig, "logistic" = ds <- stats::dlogis(z) / sig, "exponential" = ds <- stats::dexp(z) / sig ) ps <- p_std(z, distribution) # Compute log-likelihood: logL_i <- d * log(ds) + (1 - d) * log(1 - ps) logL <- sum(wts * logL_i) logL } #' Log-Likelihood Profile Function for Parametric Lifetime Distributions with Threshold #' #' @description #' This function evaluates the log-likelihood with respect to a given threshold #' parameter of a parametric lifetime distribution. In terms of #' *Maximum Likelihood Estimation* this function can be optimized #' ([optim][stats::optim]) to estimate the threshold parameter. #' #' #' @inheritParams ml_estimation #' @param thres A numeric value for the threshold parameter. #' @param distribution Supposed parametric distribution of the random variable. #' #' @return #' Returns the log-likelihood value for the threshold parameter `thres` given #' the data. #' #' @encoding UTF-8 #' #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' data <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Determining the optimal loglikelihood value: #' ## Range of threshold parameter must be smaller than the first failure: #' threshold <- seq( #' 0, #' min(data$x[data$status == 1]) - 0.1, #' length.out = 50 #' ) #' #' ## loglikelihood value with respect to threshold values: #' profile_logL <- loglik_profiling( #' x = data, #' thres = threshold, #' distribution = "weibull3" #' ) #' #' ## Threshold value (among the candidates) that maximizes the #' ## loglikelihood: #' threshold[which.max(profile_logL)] #' #' ## plot: #' plot( #' threshold, #' profile_logL, #' type = "l" #' ) #' abline( #' v = threshold[which.max(profile_logL)], #' h = max(profile_logL), #' col = "red" #' ) #' #' @md #' #' @export loglik_profiling <- function(x, ...) { UseMethod("loglik_profiling") } #' @rdname loglik_profiling #' #' @export loglik_profiling.wt_reliability_data <- function( x, wts = rep(1, nrow(x)), thres, distribution = c( "weibull3", "lognormal3", "loglogistic3", "exponential2" ), ... ) { # Call `loglik_profiling.default()`: loglik_profiling.default( x = x$x, status = x$status, wts = wts, thres = thres, distribution = distribution ) } #' Log-Likelihood Profile Function for Parametric Lifetime Distributions with Threshold #' #' @inherit loglik_profiling description return references #' #' @inheritParams ml_estimation.default #' @param thres A numeric value for the threshold parameter. #' @param distribution Supposed parametric distribution of the random variable. #' #' @encoding UTF-8 #' #' @seealso [loglik_profiling] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Determining the optimal loglikelihood value: #' ## Range of threshold parameter must be smaller than the first failure: #' threshold <- seq( #' 0, #' min(cycles[status == 1]) - 0.1, #' length.out = 50 #' ) #' #' ## loglikelihood value with respect to threshold values: #' profile_logL <- loglik_profiling( #' x = cycles, #' status = status, #' thres = threshold, #' distribution = "weibull3" #' ) #' #' ## Threshold value (among the candidates) that maximizes the #' ## loglikelihood: #' threshold[which.max(profile_logL)] #' #' ## plot: #' plot( #' threshold, #' profile_logL, #' type = "l" #' ) #' abline( #' v = threshold[which.max(profile_logL)], #' h = max(profile_logL), #' col = "red" #' ) #' #' @md #' #' @export loglik_profiling.default <- function(x, status, wts = rep(1, length(x)), thres, distribution = c( "weibull3", "lognormal3", "loglogistic3", "exponential2" ), ... ) { distribution <- match.arg(distribution) loglik_prof_vectorized <- Vectorize( FUN = loglik_profiling_, vectorize.args = "thres" ) loglik_prof_vectorized( x = x, status = status, wts = wts, thres = thres, distribution = distribution ) } # Function to perform profiling with `optim()` routine: loglik_profiling_ <- function(x, status, wts, thres, distribution ) { d <- status x <- x - thres ## Restriction of threshold models, i.e. x > threshold parameter: subs <- x > 0 x <- x[subs] d <- d[subs] wts <- wts[subs] ## Set distribution to parametric version without threshold: distribution <- std_parametric(distribution) ## Initial parameters of two-parametric model: start_dist_params <- start_params( x = x, status = d, distribution = distribution ) ## Use log scale: n_par <- length(start_dist_params) start_dist_params[n_par] <- log(start_dist_params[n_par]) ## Log-Likelihood profiling: logL_profile <- stats::optim( par = start_dist_params, fn = loglik_function_, method = "BFGS", control = list(fnscale = -1), x = x, status = d, wts = wts, distribution = distribution, log_scale = TRUE ) logL_profile$value }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/likelihood_functions.R
#' MCS Delay Data #' #' @description #' Create consistent `mcs_delay_data` based on an existing `data.frame` (preferred) #' or on multiple equal length vectors. #' #' @param data Either `NULL` or a `data.frame`. If data is `NULL`, `date_1`, `date_2`, #' `time`, `status` and `id` must be vectors containing the data. Otherwise `date_1`, #' `date_2`, `time`, `status` and `id` can be either column names or column positions. #' @param date_1 A date of class `character` or `Date` in the format "yyyy-mm-dd", #' representing the earlier of the two dates belonging to a particular delay. #' Use `NA` for missing elements. #' #' If more than one delay is to be considered, use a list for the vector-based #' approach and a vector of column names or positions for the data-based approach. #' The first element is the earlier date of the first delay, the second element is the #' earlier date of the second delay, and so forth (see 'Examples'). #' @param date_2 A date of class `character` or `Date` in the format "yyyy-mm-dd". #' `date_2` is the counterpart of `date_1` and is used the same as `date_1`, just with #' the later date(s) of the particular delay(s). Use `NA` for missing elements. #' @param time Operating times. Use `NA` for missing elements. #' @param status Optional argument. If used, it must contain binary data #' (0 or 1) indicating whether a unit is a right censored observation (= 0) or a #' failure (= 1). #' #' If `status` is provided, class `wt_reliability_data` is assigned to the #' output of [mcs_delay], which enables the direct application of [estimate_cdf] #' on operating times. #' @param id Identification of every unit. #' @param .keep_all If `TRUE` keep remaining variables in `data`. #' #' @return A `tibble` with class `wt_mcs_delay_data` that is formed for the downstream #' Monte Carlo method [mcs_delay]. #' It contains the following columns (if `.keep_all = FALSE`): #' #' * Column(s) preserving the input of `date_1`. For the vector-based approach #' with unnamed input, column name(s) is (are) `date_1` #' (`date_1.1`, `date_1.2`, `...`, `date_1.i`). #' * Column(s) preserving the input of `date_2`. For the vector-based approach #' with unnamed input, column name(s) is (are) `date_2` #' (`date_2.1`, `date_2.2`, `...`, `date_2.i`). #' * `time` : Input operating times. #' * `status` (**optional**) : #' * If `is.null(status)` column `status` does not exist. #' * If `status` is provided the column contains the entered binary #' data (0 or 1). #' * `id` : Identification for every unit. #' #' If `.keep_all = TRUE`, the remaining columns of `data` are also preserved. #' #' The attributes `mcs_start_dates` and `mcs_end_dates` hold the name(s) of the #' column(s) that preserve the input of `date_1` and `date_2`. #' #' @seealso [dist_delay] for the determination of a parametric delay distribution #' and [mcs_delay] for the Monte Carlo method with respect to delays. #' #' @examples #' # Example 1 - Based on an existing data.frame/tibble and column names: #' mcs_tbl <- mcs_delay_data( #' data = field_data, #' date_1 = production_date, #' date_2 = registration_date, #' time = dis, #' status = status #' ) #' #' # Example 2 - Based on an existing data.frame/tibble and column positions: #' mcs_tbl_2 <- mcs_delay_data( #' data = field_data, #' date_1 = 7, #' date_2 = 8, #' time = 2, #' id = 1 #' ) #' #' # Example 3 - Keep all variables of the tibble/data.frame entered to argument data: #' mcs_tbl_3 <- mcs_delay_data( #' data = field_data, #' date_1 = production_date, #' date_2 = registration_date, #' time = dis, #' status = status, #' id = vin, #' .keep_all = TRUE #' ) #' #' # Example 4 - For multiple delays (data-based): #' mcs_tbl_4 <- mcs_delay_data( #' data = field_data, #' date_1 = c(production_date, repair_date), #' date_2 = c(registration_date, report_date), #' time = dis, #' status = status #' ) #' #' # Example 5 - Based on vectors: #' mcs_tbl_5 <- mcs_delay_data( #' date_1 = field_data$production_date, #' date_2 = field_data$registration_date, #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin #' ) #' #' # Example 6 - For multiple delays (vector-based): #' mcs_tbl_6 <- mcs_delay_data( #' date_1 = list(field_data$production_date, field_data$repair_date), #' date_2 = list(field_data$registration_date, field_data$report_date), #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin #' ) #' #' # Example 7 - For multiple delays (vector-based with named dates): #' mcs_tbl_7 <- mcs_delay_data( #' date_1 = list(d11 = field_data$production_date, d12 = field_data$repair_date), #' date_2 = list(d21 = field_data$registration_date, d22 = field_data$report_date), #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin #' ) #' #' @md #' #' @export mcs_delay_data <- function(data = NULL, date_1, date_2, time, status = NULL, id = NULL, .keep_all = FALSE ) { if (purrr::is_null(data)) { # Vector based approach ---------------------------------------------------- if (!is_characteristic(time)) { stop("'time' must be numeric!", call. = FALSE) } if (purrr::is_null(id)) { id <- paste0("ID", seq_along(time)) } ## Convert date_1 and date_2 to lists if they are vectors: if (!is.list(date_1)) date_1 <- list(date_1) if (!is.list(date_2)) date_2 <- list(date_2) ## Checks: purrr::walk2( .x = date_1, .y = date_2, function(e1, e2) { ### Check for different length in date_1 and date_2: if (length(e1) != length(e2)) { stop( "Elements of 'date_1' and 'date_2' differ in length!", call. = FALSE ) } ### Check for class of date_1: if (!(class(e1) %in% c("Date", "character"))) { stop( "'date_1' must be of class 'Date' or 'character'!", call. = FALSE ) } ### Check for class date_2: if (!(class(e2) %in% c("Date", "character"))) { stop( "'date_2' must be of class 'Date' or 'character'!", call. = FALSE ) } } ) ## One list for the dates: dates_list <- c(date_1, date_2) names_dates_list <- names(dates_list) if (any(trimws(names_dates_list) == "")) { stop( "Either all or no elements of 'date_1' and 'date_2' must have names!", call. = FALSE ) } if (purrr::is_null(names_dates_list)) { if (length(dates_list) == 2L) { names_dates_list <- c("date_1", "date_2") } else { index <- seq_along(date_1) names_dates_list <- c( paste0("date_1.", index), paste0("date_2.", index) ) } } if (!purrr::is_null(status)) { if (!is_status(status)) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } tbl_list <- c(dates_list, list(time, status, id)) names(tbl_list) <- c(names_dates_list, "time", "status", "id") tbl <- tibble::as_tibble(tbl_list) } else { tbl_list <- c(dates_list, list(time, id)) names(tbl_list) <- c(names_dates_list, "time", "id") tbl <- tibble::as_tibble(tbl_list) } ## Preparation of 'mcs_start_dates' and 'mcs_end_dates': n <- length(names_dates_list) characteristic_1 <- names_dates_list[1:(n / 2)] characteristic_2 <- names_dates_list[((n / 2) + 1):n] } else { # Data based approach ------------------------------------------------------ ## Checks: if (!is_characteristic(dplyr::select(data, {{time}})[[1]])) { stop("'time' must be numeric!", call. = FALSE) } purrr::walk( dplyr::select(data, {{date_1}}, {{date_2}}), ~ if (!(class(.) %in% c("Date", "character"))) { stop( "Columns specified in 'date_1' and 'date_2' must be of class", " 'Date' or 'character'!", call. = FALSE ) } ) ## Preparation of 'mcs_start_dates' and 'mcs_end_dates': characteristic_1 <- dplyr::select(data, {{date_1}}) %>% names() characteristic_2 <- dplyr::select(data, {{date_2}}) %>% names() ## Check for same length in 'date_1' and 'date_2': if (length(characteristic_1) != length(characteristic_2)) { stop( "The same number of columns must be specified in 'date_1' and 'date_2'!", call. = FALSE ) } data <- tibble::as_tibble(data) if (.keep_all) { ## If date_1 and date_2 are col positions rename() fails since cols must be named: tbl <- dplyr::rename( data, time = {{time}}, status = {{status}}, id = {{id}} ) } else { tbl <- dplyr::select( data, {{characteristic_1}}, {{characteristic_2}}, time = {{time}}, status = {{status}}, id = {{id}} ) } if (!("id" %in% names(tbl))) { tbl$id <- paste0("ID", seq_len(nrow(data))) } if ("status" %in% names(tbl)) { if (!is_status(tbl$status)) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } } ## For col positions relocate() should use names, since locations may no longer exist: names_tbl <- names(tbl)[!(names(tbl) %in% c(characteristic_1, characteristic_2))] ## MCS characteristics should have the first column positions: tbl <- dplyr::relocate(tbl, {{characteristic_1}}, {{characteristic_2}}, {{names_tbl}}) } class(tbl) <- c("wt_mcs_delay_data", class(tbl)) # Mark date columns as characteristic attr(tbl, "mcs_start_dates") <- characteristic_1 attr(tbl, "mcs_end_dates") <- characteristic_2 tbl } #' MCS Mileage Data #' #' @description #' Create consistent `mcs_mileage_data` based on an existing `data.frame` (preferred) #' or on multiple equal length vectors #' #' @param data Either `NULL` or a `data.frame`. If data is `NULL`, `mileage`, `time`, #' `status` and `id` must be vectors containing the data. Otherwise `mileage`, `time`, #' `status` and `id` can be either column names or column positions. #' @param mileage Covered distances. Use `NA` for missing elements. #' @param time Operating times. Use `NA` for missing elements. #' @param status Optional argument. If used, it must contain binary data #' (0 or 1) indicating whether a unit is a right censored observation (= 0) or a #' failure (= 1). #' #' If `status` is provided, class `wt_reliability_data` is assigned to the #' output of [mcs_mileage], which enables the direct application of [estimate_cdf] #' on distances. #' @param id Identification of every unit. #' @param .keep_all If `TRUE` keep remaining variables in `data`. #' #' @return A `tibble` with class `wt_mcs_mileage_data` that is formed for the downstream #' Monte Carlo method [mcs_mileage]. #' It contains the following columns (if `.keep_all = FALSE`): #' #' * `mileage` : Input mileages. #' * `time` : Input operating times. #' * `status` (**optional**) : #' * If `is.null(status)` column `status` does not exist. #' * If `status` is provided the column contains the entered binary #' data (0 or 1). #' * `id` : Identification for every unit. #' #' If `.keep_all = TRUE`, the remaining columns of `data` are also preserved. #' #' The attribute `mcs_characteristic` is set to `"mileage"`. #' #' @seealso [dist_mileage] for the determination of a parametric annual mileage #' distribution and [mcs_mileage] for the Monte Carlo method with respect to #' unknown distances. #' #' @examples #' # Example 1 - Based on an existing data.frame/tibble and column names: #' mcs_tbl <- mcs_mileage_data( #' data = field_data, #' mileage = mileage, #' time = dis, #' status = status #' ) #' #' # Example 2 - Based on an existing data.frame/tibble and column positions: #' mcs_tbl_2 <- mcs_mileage_data( #' data = field_data, #' mileage = 3, #' time = 2, #' id = 1 #' ) #' #' # Example 3 - Keep all variables of the tibble/data.frame entered to argument data: #' mcs_tbl_3 <- mcs_mileage_data( #' data = field_data, #' mileage = mileage, #' time = dis, #' status = status, #' id = vin, #' .keep_all = TRUE #' ) #' #' # Example 4 - Based on vectors: #' mcs_tbl_4 <- mcs_mileage_data( #' mileage = field_data$mileage, #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin #' ) #' #' @md #' #' @export mcs_mileage_data <- function(data = NULL, mileage, time, status = NULL, id = NULL, .keep_all = FALSE ) { if (purrr::is_null(data)) { # Vector based approach ---------------------------------------------------- if (!is_characteristic(mileage)) { stop("'mileage' must be numeric!", call. = FALSE) } if (!is_characteristic(time)) { stop("'time' must be numeric!", call. = FALSE) } if (purrr::is_null(id)) { id <- paste0("ID", seq_along(mileage)) } if (!purrr::is_null(status)) { if (!is_status(status)) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } tbl <- tibble::tibble( mileage = mileage, time = time, status = status, id = id ) } else { tbl <- tibble::tibble( mileage = mileage, time = time, id = id ) } } else { # Data based approach ------------------------------------------------------ if (!is_characteristic(dplyr::select(data, {{mileage}})[[1]])) { stop("'mileage' must be numeric!", call. = FALSE) } if (!is_characteristic(dplyr::select(data, {{time}})[[1]])) { stop("'time' must be numeric!", call. = FALSE) } data <- tibble::as_tibble(data) if (.keep_all) { tbl <- dplyr::rename( data, mileage = {{mileage}}, time = {{time}}, status = {{status}}, id = {{id}} ) } else { tbl <- dplyr::select( data, mileage = {{mileage}}, time = {{time}}, status = {{status}}, id = {{id}} ) } if (!("id" %in% names(tbl))) { tbl$id <- paste0("ID", seq_len(nrow(data))) } if ("status" %in% names(tbl)) { if (!is_status(tbl$status)) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } tbl <- dplyr::relocate(tbl, "mileage", "time", "status", "id") } else { tbl <- dplyr::relocate(tbl, "mileage", "time", "id") } } class(tbl) <- c("wt_mcs_mileage_data", class(tbl)) # Mark column mileage as characteristic attr(tbl, "mcs_characteristic") <- "mileage" tbl } #' @export print.wt_mcs_mileage_data <- function(x, ...) { cat( "MCS Mileage Data with characteristic '", attr(x, "mcs_characteristic"), "':\n", sep = "" ) NextMethod() } #' @export print.wt_mcs_delay_data <- function(x, ...) { if (length(attr(x, "mcs_start_dates")) == 1L) { start <- "start date: " end <- "end date: " } else { start <- "start dates: " end <- "end dates: " } cat( "MCS Delay Data with characteristics\n", start, paste0("'", attr(x, "mcs_start_dates"), "'", collapse = ", "), "\tand\n", # 1 tab! end, paste0("'", attr(x, "mcs_end_dates"), "'", collapse = ", "), "\n", sep = "" ) NextMethod() }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/mcs_data.R
#' Adjustment of Operating Times by Delays using a Monte Carlo Approach #' #' @description #' #' In general, the amount of available information about units in the field is very #' different. During the warranty period, there are only a few cases with complete #' data (mainly *failed units*) but lots of cases with incomplete data (usually #' *censored units*). As a result, the operating time of units with incomplete #' information is often inaccurate and must be adjusted by delays. #' #' This function reduces the operating times of incomplete observations by simulated #' delays (in days). A unit is considered as incomplete if the later of the #' related dates is unknown. See 'Details' for some practical examples. #' #' Random delay numbers are drawn from the distribution determined by complete cases #' (described in 'Details' of [dist_delay]). #' #' @details #' In field data analysis time-dependent characteristics (e.g. *time in service*) #' are often imprecisely recorded. These inaccuracies are caused by unconsidered delays. #' #' For a better understanding of the MCS application in the context of field data, #' two cases are described below. #' #' * **Delay in registration**: It is common that a supplier, which provides #' parts to the manufacturing industry does not know when the unit, in which #' its parts are installed, were put in service (due to unknown registration or #' sales date (`date_2`)). Without taking the described delay into account, the #' time in service of the failed units would be the difference between the #' repair date and the production date (`date_1`) and for intact units the #' difference between the present date and the production date. But the real #' operating times are (much) shorter, since the stress on the components have #' not started until the whole systems were put in service. Hence, units with #' incomplete data (missing `date_2`) must be reduced by the delays. #' * **Delay in report**:: Authorized repairers often do not immediately #' notify the manufacturer or OEM of repairs that were made during the warranty #' period, but instead pass the information about these repairs in collected #' forms e.g. weekly, monthly or quarterly. The resulting time difference between #' the reporting (`date_2`) of the repair in the guarantee database and the #' actual repair date (`date_1`), which is often assumed to be the failure #' date, is called the reporting delay. For a given date where the analysis #' is made there could be units which had a failure but the failure isn't #' reported and therefore they are treated as censored units. In order to take #' this into account and according to the principle of equal opportunities, the #' lifetime of units with missing report date (`date_2[i] = NA`) is reduced by #' simulated reporting delays. #' #' @inheritParams dist_delay #' #' @return A list with class `wt_mcs_delay` containing the following elements: #' #' * `data` : A `tibble` returned by [mcs_delay_data] where two modifications #' has been made: #' #' * If the column `status` exists, the `tibble` has additional classes #' `wt_mcs_data` and `wt_reliability_data`. Otherwise, the `tibble` only has #' the additional class `wt_mcs_data` (which is not supported by [estimate_cdf]). #' * The column `time` is renamed to `x` (to be in accordance with #' [reliability_data]) and contains the adjusted operating times for incomplete #' observations and input operating times for the complete observations. #' #' * `sim_data` : A `tibble` with column `sim_delay` that holds the simulated #' delay-specific numbers for incomplete cases and `0` for complete cases. #' If more than one delay was considered multiple columns with names `sim_delay_1`, #' `sim_delay_2`, ..., `sim_delay_i` and corresponding delay-specific random #' numbers are presented. #' * `model_estimation` : A list returned by [dist_delay]. #' #' @references Verband der Automobilindustrie e.V. (VDA); Qualitätsmanagement in #' der Automobilindustrie. Zuverlässigkeitssicherung bei Automobilherstellern #' und Lieferanten. Zuverlässigkeits-Methoden und -Hilfsmittel.; 4th Edition, 2016, #' ISSN:0943-9412 #' #' @seealso [dist_delay] for the determination of a parametric delay distribution #' and [estimate_cdf] for the estimation of failure probabilities. #' #' @examples #' # MCS data preparation: #' ## Data for delay in registration: #' mcs_tbl_1 <- mcs_delay_data( #' field_data, #' date_1 = production_date, #' date_2 = registration_date, #' time = dis, #' status = status, #' id = vin #' ) #' #' ## Data for delay in report: #' mcs_tbl_2 <- mcs_delay_data( #' field_data, #' date_1 = repair_date, #' date_2 = report_date, #' time = dis, #' status = status, #' id = vin #' ) #' #' ## Data for both delays: #' mcs_tbl_both <- mcs_delay_data( #' field_data, #' date_1 = c(production_date, repair_date), #' date_2 = c(registration_date, report_date), #' time = dis, #' status = status, #' id = vin #' ) #' #' # Example 1 - MCS for delay in registration: #' mcs_regist <- mcs_delay( #' x = mcs_tbl_1, #' distribution = "lognormal" #' ) #' #' # Example 2 - MCS for delay in report: #' mcs_report <- mcs_delay( #' x = mcs_tbl_2, #' distribution = "exponential" #' ) #' #' # Example 3 - Reproducibility of random numbers: #' set.seed(1234) #' mcs_report_reproduce <- mcs_delay( #' x = mcs_tbl_2, #' distribution = "exponential" #' ) #' #' # Example 4 - MCS for delays in registration and report with same distribution: #' mcs_delays <- mcs_delay( #' x = mcs_tbl_both, #' distribution = "lognormal" #' ) #' #' # Example 5 - MCS for delays in registration and report with different distributions: #' ## Assuming lognormal registration and exponential reporting delays. #' mcs_delays_2 <- mcs_delay( #' x = mcs_tbl_both, #' distribution = c("lognormal", "exponential") #' ) #' #' @md #' #' @export mcs_delay <- function(...) { UseMethod("mcs_delay") } #' @rdname mcs_delay #' #' @export mcs_delay.wt_mcs_delay_data <- function( ..., x, distribution = c("lognormal", "exponential") ) { # Check that '...' argument is not used: check_dots(...) # Extract 'mcs_start_dates', 'mcs_end_dates' and 'time 'columns as list: date_1_names <- attr(x, "mcs_start_dates") date_2_names <- attr(x, "mcs_end_dates") date_1 <- dplyr::select(x, {{date_1_names}}) date_2 <- dplyr::select(x, {{date_2_names}}) time <- x$time mcs_delay_( data = x, date_1 = date_1, date_2 = date_2, time = time, distribution = distribution ) } #' Adjustment of Operating Times by Delays using a Monte Carlo Approach #' #' @inherit mcs_delay description details return references seealso #' #' @inheritParams dist_delay.default #' @inheritParams mcs_delay_data #' #' @examples #' # Example 1 - MCS for delay in registration: #' mcs_regist <- mcs_delay( #' date_1 = field_data$production_date, #' date_2 = field_data$registration_date, #' time = field_data$dis, #' status = field_data$status, #' distribution = "lognormal" #' ) #' #' # Example 2 - MCS for delay in report: #' mcs_report <- mcs_delay( #' date_1 = field_data$repair_date, #' date_2 = field_data$report_date, #' time = field_data$dis, #' status = field_data$status, #' distribution = "exponential" #' ) #' #' # Example 3 - Reproducibility of random numbers: #' set.seed(1234) #' mcs_report_reproduce <- mcs_delay( #' date_1 = field_data$repair_date, #' date_2 = field_data$report_date, #' time = field_data$dis, #' status = field_data$status, #' distribution = "exponential" #' ) #' #' # Example 4 - MCS for delays in registration and report with same distribution: #' mcs_delays <- mcs_delay( #' date_1 = list(field_data$production_date, field_data$repair_date), #' date_2 = list(field_data$registration_date, field_data$report_date), #' time = field_data$dis, #' status = field_data$status, #' distribution = "lognormal" #' ) #' #' # Example 5 - MCS for delays in registration and report with different distributions: #' ## Assuming lognormal registration and exponential reporting delays. #' mcs_delays_2 <- mcs_delay( #' date_1 = list(field_data$production_date, field_data$repair_date), #' date_2 = list(field_data$registration_date, field_data$report_date), #' time = field_data$dis, #' status = field_data$status, #' distribution = c("lognormal", "exponential") #' ) #' #' @md #' #' @export mcs_delay.default <- function(..., date_1, date_2, time, status = NULL, id = paste0("ID", seq_len(length(time))), distribution = c("lognormal", "exponential") ) { # Checks: ## Check that '...' argument is not used: check_dots(...) ## Convert date_1 and date_2 to lists if they are vectors: if (!is.list(date_1)) date_1 <- list(date_1) if (!is.list(date_2)) date_2 <- list(date_2) mcs_delay_( date_1 = date_1, date_2 = date_2, time = time, status = status, id = id, distribution = distribution ) } # Helper function that performs MCS for delays: mcs_delay_ <- function(data = NULL, date_1, # list date_2, # list time, # vector status = NULL, id = NULL, distribution ) { # Step 1: Parameter estimation using complete cases: ## Several checks (distributional and length) are made in dist_delay.default: par_list <- dist_delay.default( date_1 = date_1, date_2 = date_2, distribution = distribution ) ## New check is needed since dist_delay.default is used in favour of dist_delay_: if (!inherits(par_list, "wt_delay_estimation_list")) { par_list <- list(par_list) } # Step 2: Simulation of random numbers: sim_list <- purrr::map2( date_2, par_list, # list with class mcs_helper ) ## Adjustment of operating times: times <- time - purrr::reduce(sim_list, `+`) # Step 3: Create output: ## Create MCS_Delay_Data and renaming 'time' to 'x': ## vector-based: if (purrr::is_null(data)) { data_tbl <- mcs_delay_data( date_1 = date_1, date_2 = date_2, time = times, status = status, id = id ) } else { ## data-based: only 'time' must be updated! data_tbl <- dplyr::mutate(data, time = times) } data_tbl <- dplyr::rename(data_tbl, x = "time") ## Set class and attribute w.r.t status; remove class "wt_mcs_delay_data": if ("status" %in% names(data_tbl)) { class(data_tbl) <- c("wt_reliability_data", "wt_mcs_data", class(data_tbl)[-1]) attr(data_tbl, "characteristic") <- "time" } else { class(data_tbl) <- c("wt_mcs_data", class(data_tbl)[-1]) } # Remove attribute "mcs_start_dates" and "mcs_end_dates": attr(data_tbl, "mcs_start_dates") <- NULL attr(data_tbl, "mcs_end_dates") <- NULL ## Set names of sim_list w.r.t number of considered delays: if (length(sim_list) > 1) { names(sim_list) <- paste0("sim_delay_", seq_along(sim_list)) } else { names(sim_list) <- "sim_delay" par_list <- par_list[[1]] } mcs_output <- list( data = data_tbl, sim_data = tibble::as_tibble(sim_list), model_estimation = list( delay_distribution = par_list ) ) class(mcs_output) <- c("wt_mcs_delay", class(mcs_output)) mcs_output } # Helper function to generate MCS random numbers: mcs_helper <- function(x, par_list) { # adjustment can only be done for units that have a x entry of NA! Otherwise # data would be complete and no simulation is needed. replacable <- is.na(x) # generate random numbers: if (par_list$distribution == "lognormal") { x_sim <- stats::rlnorm( length(x), par_list$coefficients[1], par_list$coefficients[2] ) } if (par_list$distribution == "exponential") { x_sim <- stats::rexp( length(x), 1 / par_list$coefficients[1] ) } x_sim[!replacable] <- 0 x_sim } #' Adjustment of Operating Times by Delays in Registration using a Monte Carlo #' Approach #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `mcs_delay_register()` is no longer under active development, switching #' to [mcs_delay] is recommended. #' #' @details #' In general the amount of information about units in the field, that have not #' failed yet, are rare. For example it is common that a supplier, who provides #' parts to the automotive industry does not know when a vehicle was put in #' service and therefore does not know the exact operating time of the supplied #' parts. This function uses a Monte Carlo approach for simulating the operating #' times of (multiple) right censored observations, taking account of registering #' delays. The simulation is based on the distribution of operating times that were #' calculated from complete data (see [dist_delay_register]). #' #' @inheritParams dist_delay_register #' @param time A numeric vector of operating times. #' @param status A vector of binary data (0 or 1) indicating whether unit *i* is #' a right censored observation (= 0) or a failure (= 1). #' @param distribution Supposed distribution of the random variable. Only #' `"lognormal"` is implemented. #' @param details A logical. If `FALSE` the output consists of a vector with #' corrected operating times for the censored units and the input operating #' times for the failed units. If `TRUE` the output consists of a detailed #' list, i.e the same vector as described before, simulated random numbers and #' estimated distribution parameters. #' #' @return A numeric vector of corrected operating times for the censored units #' and the input operating times for the failed units if `details = FALSE`. #' If `details = TRUE` the output is a list which consists of the following elements: #' #' * `time` : Numeric vector of corrected operating times for the censored #' observations and input operating times for failed units. #' * `x_sim` : Simulated random numbers of specified distribution with estimated #' parameters. The length of `x_sim` is equal to the number of censored observations. #' * `coefficients` : Estimated coefficients of supposed distribution. #' #' @examples #' date_of_production <- c("2014-07-28", "2014-02-17", "2014-07-14", #' "2014-06-26", "2014-03-10", "2014-05-14", #' "2014-05-06", "2014-03-07", "2014-03-09", #' "2014-04-13", "2014-05-20", "2014-07-07", #' "2014-01-27", "2014-01-30", "2014-03-17", #' "2014-02-09", "2014-04-14", "2014-04-20", #' "2014-03-13", "2014-02-23", "2014-04-03", #' "2014-01-08", "2014-01-08") #' date_of_registration <- c(NA, "2014-03-29", "2014-12-06", "2014-09-09", #' NA, NA, "2014-06-16", NA, "2014-05-23", #' "2014-05-09", "2014-05-31", NA, "2014-04-13", #' NA, NA, "2014-03-12", NA, "2014-06-02", #' NA, "2014-03-21", "2014-06-19", NA, NA) #' #' op_time <- rep(1000, length(date_of_production)) #' status <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0) #' #' # Example 1 - Simplified vector output: #' x_corrected <- mcs_delay_register( #' date_prod = date_of_production, #' date_register = date_of_registration, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = FALSE #' ) #' #' # Example 2 - Detailed list output: #' list_detail <- mcs_delay_register( #' date_prod = date_of_production, #' date_register = date_of_registration, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = TRUE #' ) #' #' @md #' #' @export mcs_delay_register <- function(date_prod, date_register, time, status, distribution = "lognormal", details = FALSE ) { deprecate_soft("2.0.0", "mcs_delay_register()", "mcs_delay()") # Number of Monte Carlo simulated random numbers, i.e. number of censored data. n_rand <- sum(is.na(date_register)) if (any(!stats::complete.cases(date_prod) | !stats::complete.cases(date_register))) { prod_date <- date_prod[(stats::complete.cases(date_prod) & stats::complete.cases(date_register))] register_date <- date_register[(stats::complete.cases(date_prod) & stats::complete.cases(date_register))] } else { prod_date <- date_prod register_date <- date_register } if (distribution == "lognormal") { params <- dist_delay_register(date_prod = prod_date, date_register = register_date, distribution = "lognormal") x_sim <- stats::rlnorm(n = n_rand, meanlog = params[[1]], sdlog = params[[2]]) } else { stop("No valid distribution!", call. = FALSE) } time[is.na(date_register)] <- time[is.na(date_register)] - x_sim if (details == FALSE) { output <- time } else { output <- list(time = time, x_sim = x_sim, coefficients = params) } return(output) } #' Adjustment of Operating Times by Delays in Report using a Monte Carlo Approach #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `mcs_delay_report()` is no longer under active development, switching to #' [mcs_delay] is recommended. #' #' @details #' The delay in report describes the time between the occurrence of a damage and #' the registration in the warranty database. For a given date where the analysis #' is made there could be units which had a failure but are not registered in the #' database and therefore treated as censored units. To overcome this problem #' this function uses a Monte Carlo approach for simulating the operating #' times of (multiple) right censored observations, taking account of reporting #' delays. The simulation is based on the distribution of operating times that were #' calculated from complete data, i.e. failed items (see [dist_delay_report]). #' #' @inheritParams dist_delay_report #' @inheritParams mcs_delay_register #' #' @return A numeric vector of corrected operating times for the censored units #' and the input operating times for the failed units if `details = FALSE`. #' If `details = TRUE` the output is a list which consists of the following #' elements: #' #' * `time` : Numeric vector of corrected operating times for the censored #' observations and input operating times for failed units. #' * `x_sim` : Simulated random numbers of specified distribution with #' estimated parameters. The length of `x_sim` is equal to the number of #' censored observations. #' * `coefficients` : Estimated coefficients of supposed distribution. #' #' @examples #' date_of_repair <- c(NA, "2014-09-15", "2015-07-04", "2015-04-10", NA, #' NA, "2015-04-24", NA, "2015-04-25", "2015-04-24", #' "2015-06-12", NA, "2015-05-04", NA, NA, #' "2015-05-22", NA, "2015-09-17", NA, "2015-08-15", #' "2015-11-26", NA, NA) #' #' date_of_report <- c(NA, "2014-10-09", "2015-08-28", "2015-04-15", NA, #' NA, "2015-05-16", NA, "2015-05-28", "2015-05-15", #' "2015-07-11", NA, "2015-08-14", NA, NA, #' "2015-06-05", NA, "2015-10-17", NA, "2015-08-21", #' "2015-12-02", NA, NA) #' #' op_time <- rep(1000, length(date_of_repair)) #' status <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0) #' #' # Example 1 - Simplified vector output: #' x_corrected <- mcs_delay_report( #' date_repair = date_of_repair, #' date_report = date_of_report, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = FALSE #' ) #' #' # Example 2 - Detailed list output: #' list_detail <- mcs_delay_report( #' date_repair = date_of_repair, #' date_report = date_of_report, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = TRUE #' ) #' #' @md #' #' @export mcs_delay_report <- function(date_repair, date_report, time, status, distribution = "lognormal", details = FALSE ) { deprecate_soft("2.0.0", "mcs_delay_report()", "mcs_delay()") # Number of Monte Carlo simulated random numbers, i.e. number of censored data. n_rand <- sum(status == 0) if (any(!stats::complete.cases(date_repair) | !stats::complete.cases(date_report))) { repair_date <- date_repair[(stats::complete.cases(date_repair) & stats::complete.cases(date_report))] report_date <- date_report[(stats::complete.cases(date_repair) & stats::complete.cases(date_report))] } else { repair_date <- date_repair report_date <- date_report } if (distribution == "lognormal") { params <- dist_delay_report(date_repair = repair_date, date_report = report_date, distribution = "lognormal") x_sim <- stats::rlnorm(n = n_rand, meanlog = params[[1]], sdlog = params[[2]]) } else { stop("No valid distribution!", call. = FALSE) } time[status == 0] <- time[status == 0] - x_sim if (details == FALSE) { output <- time } else { output <- list(time = time, x_sim = x_sim, coefficients = params) } return(output) } #' Adjustment of Operating Times by Delays using a Monte Carlo Approach #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `mcs_delays()` is no longer under active development, switching to [mcs_delay] #' is recommended. #' #' @details #' This function is a wrapper that combines both, [mcs_delay_register] and #' [mcs_delay_report] functions for the adjustment of operating times of censored units. #' #' @inheritParams mcs_delay_register #' @inheritParams dist_delay_report #' #' @return A numerical vector of corrected operating times for the censored units #' and the input operating times for the failed units if #' `details = FALSE`. If `details = TRUE` the output is a list which #' consists of the following elements: #' #' * `time` : A numeric vector of corrected operating times for the censored #' observations and input operating times for failed units. #' * `x_sim_regist` : Simulated random numbers of specified distribution with #' estimated parameters for delay in registration. The length of `x_sim_regist` #' is equal to the number of censored observations. #' * `x_sim_report` : Simulated random numbers of specified distribution with #' estimated parameters for delay in report. The length of `x_sim_report` is #' equal to the number of censored observations. #' * `coefficients_regist` : Estimated coefficients of supposed distribution for #' delay in registration. #' * `coefficients_report` : Estimated coefficients of supposed distribution for #' delay in report #' #' @examples #' date_of_production <- c("2014-07-28", "2014-02-17", "2014-07-14", #' "2014-06-26", "2014-03-10", "2014-05-14", #' "2014-05-06", "2014-03-07", "2014-03-09", #' "2014-04-13", "2014-05-20", "2014-07-07", #' "2014-01-27", "2014-01-30", "2014-03-17", #' "2014-02-09", "2014-04-14", "2014-04-20", #' "2014-03-13", "2014-02-23", "2014-04-03", #' "2014-01-08", "2014-01-08") #' date_of_registration <- c("2014-08-17", "2014-03-29", "2014-12-06", #' "2014-09-09", "2014-05-14", "2014-07-01", #' "2014-06-16", "2014-04-03", "2014-05-23", #' "2014-05-09", "2014-05-31", "2014-08-12", #' "2014-04-13", "2014-02-15", "2014-07-07", #' "2014-03-12", "2014-05-27", "2014-06-02", #' "2014-05-20", "2014-03-21", "2014-06-19", #' "2014-02-12", "2014-03-27") #' date_of_repair <- c(NA, "2014-09-15", "2015-07-04", "2015-04-10", NA, #' NA, "2015-04-24", NA, "2015-04-25", "2015-04-24", #' "2015-06-12", NA, "2015-05-04", NA, NA, #' "2015-05-22", NA, "2015-09-17", NA, "2015-08-15", #' "2015-11-26", NA, NA) #' #' date_of_report <- c(NA, "2014-10-09", "2015-08-28", "2015-04-15", NA, #' NA, "2015-05-16", NA, "2015-05-28", "2015-05-15", #' "2015-07-11", NA, "2015-08-14", NA, NA, #' "2015-06-05", NA, "2015-10-17", NA, "2015-08-21", #' "2015-12-02", NA, NA) #' #' op_time <- rep(1000, length(date_of_repair)) #' status <- c(0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0) #' #' # Example 1 - Simplified vector output: #' x_corrected <- mcs_delays( #' date_prod = date_of_production, #' date_register = date_of_registration, #' date_repair = date_of_repair, #' date_report = date_of_report, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = FALSE #' ) #' #' # Example 2 - Detailed list output: #' list_detail <- mcs_delays( #' date_prod = date_of_production, #' date_register = date_of_registration, #' date_repair = date_of_repair, #' date_report = date_of_report, #' time = op_time, #' status = status, #' distribution = "lognormal", #' details = TRUE #' ) #' #' @md #' #' @export mcs_delays <- function(date_prod, date_register, date_repair, date_report, time, status, distribution = "lognormal", details = FALSE ) { deprecate_soft("2.0.0", "mcs_delays()", "mcs_delay()") # Number of Monte Carlo simulated random numbers, i.e. number of censored data. n_rand_regist <- sum(is.na(date_register)) n_rand_report <- sum(status == 0) if (any(!stats::complete.cases(date_prod) | !stats::complete.cases(date_register))) { prod_date <- date_prod[(stats::complete.cases(date_prod) & stats::complete.cases(date_register))] register_date <- date_register[(stats::complete.cases(date_prod) & stats::complete.cases(date_register))] } else { prod_date <- date_prod register_date <- date_register } if (any(!stats::complete.cases(date_repair) | !stats::complete.cases(date_report))) { repair_date <- date_repair[(stats::complete.cases(date_repair) & stats::complete.cases(date_report))] report_date <- date_report[(stats::complete.cases(date_repair) & stats::complete.cases(date_report))] } else { repair_date <- date_repair report_date <- date_report } if (distribution == "lognormal") { params_regist <- dist_delay_register(date_prod = prod_date, date_register = register_date, distribution = "lognormal") params_report <- dist_delay_report(date_repair = repair_date, date_report = report_date, distribution = "lognormal") x_sim_regist <- stats::rlnorm(n = n_rand_regist, meanlog = params_regist[[1]], sdlog = params_regist[[2]]) x_sim_report <- stats::rlnorm(n = n_rand_report, meanlog = params_report[[1]], sdlog = params_report[[2]]) } else { stop("No valid distribution!", call. = FALSE) } time[is.na(date_register)] <- time[is.na(date_register)] - x_sim_regist time[status == 0] <- time[status == 0] - x_sim_report if (details == FALSE) { output <- time } else { output <- list(time = time, x_sim_regist = x_sim_regist, x_sim_report = x_sim_report, coefficients_regist = params_regist, coefficients_report = params_report) } return(output) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/mcs_delay.R
#' Simulation of Unknown Covered Distances using a Monte Carlo Approach #' #' @description #' This function simulates distances for units where these are unknown. #' #' First, random numbers of the annual mileage distribution, estimated by #' [dist_mileage], are drawn. Second, the drawn annual distances are #' converted with respect to the actual operating times (in days) using a linear #' relationship. See 'Details'. #' #' @details #' **Assumption of linear relationship**: Imagine the distance of the vehicle #' is unknown. A distance of 3500.25 kilometers (km) was drawn from the annual #' distribution and the known operating time is 200 days (d). So the resulting #' distance of this vehicle is #' \deqn{3500.25 km \cdot (\frac{200 d} {365 d}) = 1917.945 km}{% #' 3500.25 km * (200 d / 365 d) = 1917.945 km} #' #' @inheritParams dist_mileage #' #' @return A list with class `wt_mcs_mileage` containing the following elements: #' #' * `data` : A `tibble` returned by [mcs_mileage_data] where two modifications #' has been made: #' #' * If the column `status` exists, the `tibble` has additional classes #' `wt_mcs_data` and `wt_reliability_data`. Otherwise, the `tibble` only has #' the additional class `wt_mcs_data` (which is not supported by [estimate_cdf]). #' * The column `mileage` is renamed to `x` (to be in accordance with #' [reliability_data]) and contains simulated distances for incomplete #' observations and input distances for the complete observations. #' * `sim_data` : A `tibble` with column `sim_mileage` that holds the simulated #' distances for incomplete cases and `0` for complete cases. #' * `model_estimation` : A list returned by [dist_mileage]. #' #' @seealso [dist_mileage] for the determination of a parametric annual mileage #' distribution and [estimate_cdf] for the estimation of failure probabilities. #' #' @examples #' # MCS data preparation: #' mcs_tbl <- mcs_mileage_data( #' field_data, #' mileage = mileage, #' time = dis, #' status = status, #' id = vin #' ) #' #' # Example 1 - Reproducibility of drawn random numbers: #' set.seed(1234) #' mcs_distances <- mcs_mileage( #' x = mcs_tbl, #' distribution = "lognormal" #' ) #' #' # Example 2 - MCS for distances with exponential annual mileage distribution: #' mcs_distances_2 <- mcs_mileage( #' x = mcs_tbl, #' distribution = "exponential" #' ) #' #' # Example 3 - MCS for distances with downstream probability estimation: #' ## Apply 'estimate_cdf()' to *$data: #' prob_estimation <- estimate_cdf( #' x = mcs_distances$data, #' methods = "kaplan" #' ) #' #' ## Apply 'plot_prob()': #' plot_prob_estimation <- plot_prob(prob_estimation) #' #' @md #' #' @export mcs_mileage <- function(x, ...) { UseMethod("mcs_mileage") } #' @rdname mcs_mileage #' #' @export mcs_mileage.wt_mcs_mileage_data <- function( x, distribution = c("lognormal", "exponential"), ... ) { # Checks: ## Check for distributions: distribution <- match.arg(distribution) mileage <- x$mileage time <- x$time mcs_mileage_( data = x, x = mileage, time = time, distribution = distribution ) } #' Simulation of Unknown Covered Distances using a Monte Carlo Approach #' #' @inherit mcs_mileage description details return seealso #' #' @inheritParams dist_mileage.default #' @inheritParams mcs_mileage_data #' #' @examples #' # Example 1 - Reproducibility of drawn random numbers: #' set.seed(1234) #' mcs_distances <- mcs_mileage( #' x = field_data$mileage, #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin, #' distribution = "lognormal" #' ) #' #' # Example 2 - MCS for distances with exponential annual mileage distribution: #' mcs_distances_2 <- mcs_mileage( #' x = field_data$mileage, #' time = field_data$dis, #' status = field_data$status, #' id = field_data$vin, #' distribution = "exponential" #' ) #' #' # Example 3 - MCS for distances with downstream probability estimation: #' ## Apply 'estimate_cdf()' to *$data: #' prob_estimation <- estimate_cdf( #' x = mcs_distances$data, #' methods = "kaplan" #' ) #' #' ## Apply 'plot_prob()': #' plot_prob_estimation <- plot_prob(prob_estimation) #' #' @md #' #' @export mcs_mileage.default <- function(x, time, status = NULL, id = paste0("ID", seq_len(length(time))), distribution = c("lognormal", "exponential"), ... ) { # Checks: ## Check for distributions: distribution <- match.arg(distribution) ## Check for different length in time and x: if (length(x) != length(time)) { stop("Elements of 'x' and 'time' differ in length!", call. = FALSE) } mcs_mileage_( x = x, time = time, status = status, id = id, distribution = distribution ) } # Helper function that performs MCS for distances: mcs_mileage_ <- function(data = NULL, x, # vector time, # vector, status = NULL, id = NULL, distribution ) { # Step 1: Parameter estimation using complete cases: par_list <- dist_mileage.default( x = x, time = time, distribution = distribution ) # Step 2: Simulation of random numbers: sim_nums <- mcs_helper( x = x, par_list = par_list ) ## Imputation of missing mileages: x[is.na(x)] <- (sim_nums[is.na(x)] * time[is.na(x)]) / 365 # Step 3: Create output: ## Create MCS_Mileage_Data and renaming 'mileage' to 'x': ## vector-based: if (purrr::is_null(data)) { data_tbl <- mcs_mileage_data( mileage = x, time = time, status = status, id = id ) } else { ## data-based: only 'mileage' must be updated! data_tbl <- dplyr::mutate(data, mileage = x) } data_tbl <- dplyr::rename(data_tbl, x = "mileage") ## Set class and attribute w.r.t status; remove class "wt_mcs_mileage_data": if ("status" %in% names(data_tbl)) { class(data_tbl) <- c("wt_reliability_data", "wt_mcs_data", class(data_tbl)[-1]) attr(data_tbl, "characteristic") <- "mileage" } else { class(data_tbl) <- c("wt_mcs_data", class(data_tbl)[-1]) } # Remove attribute "mcs_characteristic": attr(data_tbl, "mcs_characteristic") <- NULL mcs_output <- list( data = data_tbl, sim_data = tibble::tibble(sim_mileage = sim_nums), model_estimation = list( mileage_distribution = par_list ) ) class(mcs_output) <- c("wt_mcs_mileage", class(mcs_output)) mcs_output }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/mcs_mileage.R
#' Parameter Estimation of an Annual Mileage Distribution #' #' @description #' This function models a mileage random variable on an annual basis with respect #' to a supposed continuous distribution. First, the distances are calculated for #' one year (365 days) using a linear relationship between the distance and #' operating time. Second, the parameter(s) of the assumed distribution are #' estimated with maximum likelihood. See 'Details' for more information. #' #' @details #' The distribution parameter(s) is (are) determined on the basis of complete #' cases, i.e. there is no `NA` (row-wise) in one of the related columns `mileage` #' and `time`. Distances and operating times less than or equal to zero are not #' considered as well. #' #' **Assumption of linear relationship**: Imagine a component in a vehicle #' has endured a distance of 25000 kilometers (km) in 500 days (d), the annual #' distance of this unit is \deqn{25000 km \cdot (\frac{365 d} {500 d}) = 18250 km}{% #' 25000 km * (365 d / 500 d) = 18250 km} #' #' @param x A `tibble` of class `wt_mcs_mileage_data` returned by [mcs_mileage_data]. #' @param distribution Supposed distribution of the annual mileage. #' @template dots #' #' @return A list with class `wt_mileage_estimation` which contains: #' #' * `coefficients` : A named vector of estimated parameter(s). #' * `miles_annual` : A numeric vector of element-wise computed annual distances #' using the linear relationship described in 'Details'. #' * `distribution` : Specified distribution. #' #' @examples #' # MCS data preparation: #' mcs_tbl <- mcs_mileage_data( #' field_data, #' mileage = mileage, #' time = dis, #' status = status, #' id = vin #' ) #' #' # Example 1 - Assuming lognormal annual mileage distribution: #' params_mileage_annual <- dist_mileage( #' x = mcs_tbl, #' distribution = "lognormal" #' ) #' #' # Example 2 - Assuming exponential annual mileage distribution: #' params_mileage_annual_2 <- dist_mileage( #' x = mcs_tbl, #' distribution = "exponential" #' ) #' #' @md #' #' @export dist_mileage <- function(x, ...) { UseMethod("dist_mileage") } #' @rdname dist_mileage #' #' @export dist_mileage.wt_mcs_mileage_data <- function( x, distribution = c("lognormal", "exponential"), ... ) { mileage <- x$mileage time <- x$time # Use default method: dist_mileage.default( x = mileage, time = time, distribution = distribution ) } #' Parameter Estimation of an Annual Mileage Distribution #' #' @inherit dist_mileage description return #' #' @details #' The distribution parameter(s) is (are) determined on the basis of complete cases, #' i.e. there is no `NA` in one of the related vector elements #' `c(mileage[i], time[i])`. Distances and operating times less than or equal #' to zero are not considered as well. #' #' **Assumption of linear relationship**: Imagine a component in a vehicle #' has endured a distance of 25000 kilometers (km) in 500 days (d), the annual #' distance of this unit is \deqn{25000 km \cdot (\frac{365 d} {500 d}) = 18250 km}{% #' 25000 km * (365 d / 500 d) = 18250 km} #' #' @inheritParams dist_mileage #' @param x A numeric vector of distances covered. Use `NA` for missing elements. #' @param time A numeric vector of operating times. Use `NA` for missing elements. #' #' @seealso [dist_mileage] #' #' @examples #' # Example 1 - Assuming lognormal annual mileage distribution: #' params_mileage_annual <- dist_mileage( #' x = field_data$mileage, #' time = field_data$dis, #' distribution = "lognormal" #' ) #' #' # Example 2 - Assuming exponential annual mileage distribution: #' params_mileage_annual_2 <- dist_mileage( #' x = field_data$mileage, #' time = field_data$dis, #' distribution = "exponential" #' ) #' #' @md #' #' @export dist_mileage.default <- function(x, time, distribution = c("lognormal", "exponential"), ... ) { # Checks: ## Distribution check: distribution <- match.arg(distribution) ## Check for negative mileage, stop if TRUE: if (any(x < 0, na.rm = TRUE)) { stop( "Elements with negative distances are not meaningful and must be removed!", call. = FALSE ) } # Do dist_mileage_(): dist_mileage_( x = x, time = time, distribution = distribution ) } # Helper function that performs the estimation of an annual mileage distribution: dist_mileage_ <- function(x, time, distribution ) { # Defining annual distance variable (for estimation) and origin variable (output): miles_annual <- miles_annual_origin <- (x / time) * 365 # Checks: ## case of Inf, i.e. time is 0: could be handled with `is.infinite()` if (any(is.infinite(miles_annual))) { warning( "At least one computed annual distance is infinite and is ignored ", "for the estimation step!", call. = FALSE ) miles_annual <- miles_annual[!is.infinite(miles_annual)] } ## all NA: if (all(is.na(miles_annual))) { stop( "All computed annual distances are 'NA'. No parameters can be estimated!", call. = FALSE ) } ## any or all annual distances are smaller or equal to zero: if (any(miles_annual <= 0, na.rm = TRUE)) { if (all(miles_annual <= 0, na.rm = TRUE)) { ### all: stop( "All computed annual distances are smaller or equal to 0. ", "No parameters can be estimated!", call. = FALSE ) } else { ### any: warning( "At least one computed annual distance is smaller or equal to 0 ", "and is ignored for the estimation step!", call. = FALSE ) miles_annual <- miles_annual[miles_annual > 0] } } if (distribution == "lognormal") { # sample size used for the computation of the population standard deviation. n <- sum(!is.na(miles_annual)) ml_loc <- mean(log(miles_annual), na.rm = TRUE) ml_sc <- stats::sd(log(miles_annual), na.rm = TRUE) * (n - 1) / n estimates <- c(loc = ml_loc, sc = ml_sc) } if (distribution == "exponential") { ml_sc <- mean(miles_annual, na.rm = TRUE) estimates <- c(sc = ml_sc) } dist_output <- list( coefficients = estimates, miles_annual = miles_annual_origin, distribution = distribution ) class(dist_output) <- c("wt_mileage_estimation", class(dist_output)) return(dist_output) } #' @export print.wt_mileage_estimation <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat("Coefficients:\n") print(format(stats::coef(x), digits = digits), print.gap = 2L, quote = FALSE) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/mileage_distribution.R
#' Mixture Model Identification using Segmented Regression #' #' @description #' This function uses piecewise linear regression to divide the data into #' subgroups. See 'Details'. #' #' @details #' The segmentation process is based on the lifetime realizations of failed #' units and their corresponding estimated failure probabilities for which intact #' items are taken into account. It is performed with the support of #' [segmented.lm][segmented::segmented]. #' #' Segmentation can be done with a specified number of subgroups or in an automated #' fashion (see argument `k`). The algorithm tends to overestimate the number of #' breakpoints when the separation is done automatically (see 'Warning' in #' [segmented.lm][segmented::segmented]). #' #' In the context of reliability analysis it is important that the main types of #' failures can be identified and analyzed separately. These are #' #' * early failures, #' * random failures and #' * wear-out failures. #' #' In order to reduce the risk of overestimation as well as being able to consider #' the main types of failures, a maximum of three subgroups (`k = 3`) is recommended. #' #' @inheritParams rank_regression.wt_cdf_estimation #' @param k Number of mixture components. If the data should be split in an #' automated fashion, `k` must be set to `NULL`. The argument `fix.psi` of #' `control` is then set to `FALSE`. #' @param control Output of the call to [seg.control][segmented::seg.control], #' which is passed to [segmented.lm][segmented::segmented]. See 'Examples' for usage. #' #' @return A list with classes `wt_model` and `wt_rank_regression` if no breakpoint #' was detected. See [rank_regression]. #' #' A list with classes `wt_model` and `wt_mixmod_regression` if at least one #' breakpoint was determined. The length of the list depends on the number of #' identified subgroups. Each list element contains the information provided by #' [rank_regression]. In addition, the returned tibble `data` of each list element #' only retains information on the failed units and has two more columns: #' #' * `q` : Quantiles of the standard distribution calculated from column `prob`. #' * `group` : Membership to the respective segment. #' #' If more than one method was specified in [estimate_cdf], the resulting output #' is a list with classes `wt_model` and `wt_mixmod_regression_list` where each #' list element has classes `wt_model` and `wt_mixmod_regression`. #' #' @encoding UTF-8 #' #' @references Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by #' Failure Mode, Quality Progress, 35(6), 47-52, 2002 #' #' @examples #' # Reliability data preparation: #' ## Data for mixture model: #' data_mix <- reliability_data( #' voltage, #' x = hours, #' status = status #' ) #' #' ## Data for simple unimodal distribution: #' data <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' # Probability estimation with one method: #' prob_mix <- estimate_cdf( #' data_mix, #' methods = "johnson" #' ) #' #' prob <- estimate_cdf( #' data, #' methods = "johnson" #' ) #' #' # Probability estimation for multiple methods: #' prob_mix_mult <- estimate_cdf( #' data_mix, #' methods = c("johnson", "kaplan", "nelson") #' ) #' #' # Example 1 - Mixture identification using k = 2 two-parametric Weibull models: #' mix_mod_weibull <- mixmod_regression( #' x = prob_mix, #' distribution = "weibull", #' conf_level = 0.99, #' k = 2 #' ) #' #' # Example 2 - Mixture identification using k = 3 two-parametric lognormal models: #' mix_mod_lognorm <- mixmod_regression( #' x = prob_mix, #' distribution = "lognormal", #' k = 3 #' ) #' #' # Example 3 - Mixture identification for multiple methods specified in estimate_cdf: #' mix_mod_mult <- mixmod_regression( #' x = prob_mix_mult, #' distribution = "loglogistic" #' ) #' #' # Example 4 - Mixture identification using control argument: #' mix_mod_control <- mixmod_regression( #' x = prob_mix, #' distribution = "weibull", #' control = segmented::seg.control(display = TRUE) #' ) #' #' # Example 5 - Mixture identification performs rank_regression for k = 1: #' mod <- mixmod_regression( #' x = prob, #' distribution = "weibull", #' k = 1 #' ) #' #' @md #' #' @export mixmod_regression <- function(x, ...) { UseMethod("mixmod_regression") } #' @rdname mixmod_regression #' #' @export mixmod_regression.wt_cdf_estimation <- function( x, distribution = c( "weibull", "lognormal", "loglogistic" ), conf_level = .95, k = 2, control = segmented::seg.control(), ... ) { distribution <- match.arg(distribution) x_split <- split(x, x$cdf_estimation_method) if (length(unique(x$cdf_estimation_method)) == 1) { out <- mixmod_regression_( cdf_estimation = x, distribution = distribution, conf_level = conf_level, k = k, control = control ) } else { out <- purrr::map(x_split, function(cdf_estimation) { mixmod_regression_( cdf_estimation = cdf_estimation, distribution = distribution, conf_level = conf_level, k = k, control = control ) }) class(out) <- c("wt_model", "wt_mixmod_regression_list", class(out)) } out } #' Mixture Model Identification using Segmented Regression #' #' @inherit mixmod_regression description details references #' #' @inheritParams rank_regression.default #' @inheritParams mixmod_regression.wt_cdf_estimation #' @param control Output of the call to [seg.control][segmented::seg.control], #' which is passed to [segmented.lm][segmented::segmented]. See 'Examples' for usage. #' #' @return A list with classes `wt_model` and `wt_rank_regression` if no breakpoint #' was detected. See [rank_regression]. The returned tibble `data` is of class #' `wt_cdf_estimation` and contains the dummy columns `cdf_estimation_method` and #' `id`. The former is filled with `NA_character`, due to internal usage and the #' latter is filled with `"XXXXXX"` to point out that unit identification is not #' possible when using the vector-based approach. #' #' A list with classes `wt_model` and `wt_mixmod_regression` if at least one #' breakpoint was determined. The length of the list depends on the number of #' identified subgroups. Each list contains the information provided by #' [rank_regression]. The returned tibble `data` of each list element only retains #' information on the failed units and has modified and additional columns: #' #' * `id` : Modified id, overwritten with `"XXXXXX"` to point out that unit #' identification is not possible when using the vector-based approach. #' * `cdf_estimation_method` : A character that is always `NA_character`. Only #' needed for internal use. #' * `q` : Quantiles of the standard distribution calculated from column `prob`. #' * `group` : Membership to the respective segment. #' #' @encoding UTF-8 #' #' @seealso [mixmod_regression] #' #' @examples #' # Vectors: #' ## Data for mixture model: #' hours <- voltage$hours #' status <- voltage$status #' #' ## Data for simple unimodal distribution: #' distance <- shock$distance #' status_2 <- shock$status #' #' # Probability estimation with one method: #' prob_mix <- estimate_cdf( #' x = hours, #' status = status, #' method = "johnson" #' ) #' #' prob <- estimate_cdf( #' x = distance, #' status = status_2, #' method = "johnson" #' ) #' #' # Example 1 - Mixture identification using k = 2 two-parametric Weibull models: #' mix_mod_weibull <- mixmod_regression( #' x = prob_mix$x, #' y = prob_mix$prob, #' status = prob_mix$status, #' distribution = "weibull", #' conf_level = 0.99, #' k = 2 #' ) #' #' # Example 2 - Mixture identification using k = 3 two-parametric lognormal models: #' mix_mod_lognorm <- mixmod_regression( #' x = prob_mix$x, #' y = prob_mix$prob, #' status = prob_mix$status, #' distribution = "lognormal", #' k = 3 #' ) #' #' # Example 3 - Mixture identification using control argument: #' mix_mod_control <- mixmod_regression( #' x = prob_mix$x, #' y = prob_mix$prob, #' status = prob_mix$status, #' distribution = "weibull", #' k = 2, #' control = segmented::seg.control(display = TRUE) #' ) #' #' # Example 4 - Mixture identification performs rank_regression for k = 1: #' mod <- mixmod_regression( #' x = prob$x, #' y = prob$prob, #' status = prob$status, #' distribution = "weibull", #' k = 1 #' ) #' #' @md #' #' @export mixmod_regression.default <- function(x, y, status, distribution = c( "weibull", "lognormal", "loglogistic" ), conf_level = .95, k = 2, control = segmented::seg.control(), ... ) { distribution <- match.arg(distribution) # mimic output of estimate_cdf cdf <- tibble::tibble( id = "XXXXXX", x = x, status = status, prob = y, cdf_estimation_method = NA_character_ ) class(cdf) <- c("wt_cdf_estimation", class(cdf)) mixmod_regression_( cdf_estimation = cdf, distribution = distribution, conf_level = conf_level, k = k, control = control ) } mixmod_regression_ <- function(cdf_estimation, distribution, conf_level, k, control ) { if (!purrr::is_null(k) && k < 1) { stop("'k' must be greater or equal than 1!", call. = FALSE) } # Preparation for segmented regression: cdf_failed <- dplyr::filter(cdf_estimation, .data$status == 1) cdf_failed$q <- q_std(cdf_failed$prob, distribution) mrr <- stats::lm(log(x) ~ q, cdf_failed) if (!purrr::is_null(k) && k == 1) { mrr_output <- rank_regression( cdf_estimation, distribution = distribution, conf_level = conf_level ) return(mrr_output) } # Segmented regression: if (purrr::is_null(k)) { message("Automated segmentation process was used", " problem of overestimation may have occured!") control$fix.npsi <- FALSE seg_mrr <- with( cdf_failed, segmented::segmented.lm( mrr, psi = NA, control = control ) ) } else { seg_mrr <- with( cdf_failed, segmented::segmented.lm( mrr, psi = quantile(q, probs = 1 / k * (1:(k - 1))), control = control ) ) } # Group membership: group_seg <- seg_mrr$id.group # Test for successful segmentation of all failed units: if (purrr::is_null(group_seg)) { # Not succeeded: stop( "Segmentation has not succeeded. Reduce 'k' in the function call!", call. = FALSE ) } # Succeeded: cdf_failed$group <- group_seg + 1 cdf_split <- split(cdf_failed, cdf_failed$group) mrr_output <- purrr::map( cdf_split, rank_regression, distribution = distribution, conf_level = conf_level ) names(mrr_output) <- paste("mod", seq_along(mrr_output), sep = "_") class(mrr_output) <- c("wt_model", "wt_mixmod_regression", class(mrr_output)) return(mrr_output) } #' @export print.wt_mixmod_regression <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat("Mixmod Regression:\n") purrr::walk2(x, seq_along(x), function(model_estimation, i) { cat(paste0("Subgroup ", i, ":\n")) indent_by(print(model_estimation), 2) }) } #' @export print.wt_mixmod_regression_list <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat(paste("List of", length(x), "mixmod regressions:\n")) purrr::walk2(x, names(x), function(mixmod_regression, method) { print(mixmod_regression) cat(paste("Method of CDF Estimation:", method, "\n")) cat("\n") }) invisible(x) } #' Weibull Mixture Model Estimation using EM-Algorithm #' #' @description #' This method applies the expectation-maximization (EM) algorithm to estimate the #' parameters of a univariate Weibull mixture model. See 'Details'. #' #' @details #' The EM algorithm is an iterative algorithm for which starting values must be #' defined. Starting values can be provided for the unknown parameter vector as #' well as for the posterior probabilities. This implementation employs initial #' values for the posterior probabilities. These are assigned randomly #' by using the Dirichlet distribution, the conjugate prior of a multinomial #' distribution (see Mr. Gelissen's blog post listed under *references*). #' #' **M-Step** : On the basis of the initial posterior probabilities, the #' parameter vector is estimated with *Newton-Raphson*. #' #' **E-Step** : The actual estimated parameter vector is used to perform an #' update of the posterior probabilities. #' #' This procedure is repeated until the complete log-likelihood has converged. #' #' @param x A tibble with class `wt_reliability_data` returned by [reliability_data]. #' @param distribution `"weibull"` until further distributions are implemented. #' @param conf_level Confidence level for the intervals of the Weibull parameters #' of every component `k`. #' @param k Number of mixture components. #' @param method `"EM"` until other methods are implemented. #' @param n_iter Integer defining the maximum number of iterations. #' @param conv_limit Numeric value defining the convergence limit. #' @param diff_loglik Numeric value defining the maximum difference between #' log-likelihood values, which seems permissible. #' @template dots #' #' @return A list with classes `wt_model` and `wt_mixmod_em`. The length of the #' list depends on the number of specified subgroups `k`. The first `k` lists #' contain information provided by [ml_estimation]. The values of `logL`, `aic` #' and `bic` are the results of a weighted log-likelihood, where the weights are #' the posterior probabilities determined by the algorithm. The last list summarizes #' further results of the EM algorithm and is therefore called `em_results`. It #' contains the following elements: #' #' * `a_priori` : A vector with estimated prior probabilities. #' * `a_posteriori` : A matrix with estimated posterior probabilities. #' * `groups` : Numeric vector specifying the group membership of every observation. #' * `logL` : The value of the complete log-likelihood. #' * `aic` : Akaike Information Criterion. #' * `bic` : Bayesian Information Criterion. #' #' @encoding UTF-8 #' #' @references #' #' * Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by Failure Mode, #' Quality Progress, 35(6), 47-52, 2002 #' #' @examples #' # Reliability data preparation: #' ## Data for mixture model: #' data_mix <- reliability_data( #' voltage, #' x = hours, #' status = status #' ) #' #' # Example 1 - EM algorithm with k = 2: #' mix_mod_em <- mixmod_em( #' x = data_mix, #' conf_level = 0.95, #' k = 2, #' n_iter = 150 #' ) #' #' # Example 2 - Maximum likelihood is applied when k = 1: #' mix_mod_em_2 <- mixmod_em( #' x = data_mix, #' conf_level = 0.95, #' k = 1, #' n_iter = 150 #' ) #' #' @md #' #' @export mixmod_em <- function(x, ...) { UseMethod("mixmod_em") } #' @rdname mixmod_em #' #' @export mixmod_em.wt_reliability_data <- function(x, distribution = "weibull", conf_level = .95, k = 2, method = "EM", n_iter = 100L, conv_limit = 1e-6, diff_loglik = 0.01, ... ) { distribution <- match.arg(distribution) method <- match.arg(method) mixmod_em_( data = x, distribution = distribution, conf_level = conf_level, k = k, method = method, n_iter = n_iter, conv_limit = conv_limit, diff_loglik = diff_loglik, drop_id = FALSE ) } #' Weibull Mixture Model Estimation using EM-Algorithm #' #' @inherit mixmod_em description details return references #' #' @inheritParams mixmod_em #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, e.g. #' operating time (days/months in service), mileage (km, miles), load cycles. #' @param status A vector of binary data (0 or 1) indicating whether a unit is a #' right censored observation (= 0) or a failure (= 1). #' #' @seealso [mixmod_em] #' #' @examples #' # Vectors: #' hours <- voltage$hours #' status <- voltage$status #' #' # Example 1 - EM algorithm with k = 2: #' mix_mod_em <- mixmod_em( #' x = hours, #' status = status, #' distribution = "weibull", #' conf_level = 0.95, #' k = 2, #' n_iter = 150 #' ) #' #'#' # Example 2 - Maximum likelihood is applied when k = 1: #' mix_mod_em_2 <- mixmod_em( #' x = hours, #' status = status, #' distribution = "weibull", #' conf_level = 0.95, #' k = 1, #' method = "EM", #' n_iter = 150 #' ) #' #' @md #' #' @export mixmod_em.default <- function(x, status, distribution = "weibull", conf_level = 0.95, k = 2, method = "EM", n_iter = 100L, conv_limit = 1e-6, diff_loglik = 0.01, ... ) { distribution <- match.arg(distribution) method <- match.arg(method) data <- reliability_data(x = x, status = status) mixmod_em_( data = data, distribution = distribution, conf_level = conf_level, k = k, method = method, n_iter = n_iter, conv_limit = conv_limit, diff_loglik = diff_loglik, drop_id = TRUE ) } mixmod_em_ <- function(data, distribution, conf_level, k, method, n_iter, conv_limit, diff_loglik, drop_id ) { x <- data$x status <- data$status # Providing initial random a-posteriors (see references, blog post Mr. Gelissen): post <- rdirichlet(n = length(x), par = rep(0.1, k)) # mixture_em_cpp() for applying EM-Algorithm: mix_est <- mixture_em_cpp( x = x, status = status, post = post, distribution = distribution, k = k, method = method, n_iter = n_iter, conv_limit = conv_limit ) ############## New Approach ############## # Try to apply ml_estimation where observations are weighted with a-posterioris: ml <- try( apply( mix_est$posteriori, MARGIN = 2, FUN = ml_estimation, x = data, distribution = distribution, conf_level = conf_level ), silent = TRUE ) if (inherits(ml, "try-error")) { stop( paste( ml[1], sprintf("\n For k = %s subcomponents the above problem occured!", k), "\n Hint: Reduce k in function call and try again. If this does", "not succeed a mixture model seems not to be appropriate.", "\n Instead use k = 1 to perform ml_estimation()." ), call. = FALSE ) } # calculate complete log-likelihood and information criteria for EM. logL_comps <- sapply(ml, "[[", "logL") logL_complete <- sum(logL_comps) + sum(mix_est$posteriori %*% log(mix_est$priori)) aic_complete <- -2 * logL_complete + 2 * (2 * k + (k - 1)) bic_complete <- -2 * logL_complete + log(length(x)) * (2 * k + (k - 1)) # Check whether log-likelihood from mixture_em_cpp() and complete log-likelihood # after recalculating parameters with ml_estimation() are close to each other. # If so, appearance of a mixture is strengthened and a good fit is reliable. # Otherwise, stop() function should be called, since posterioris and prioris are # not valid anymore!!!! if (abs(logL_complete - mix_est$logL) > diff_loglik) { stop("Parameter estimation was not successful!", call. = FALSE) } # separate observations using maximum a-posteriori method (MAP): split_obs <- apply(mix_est$posteriori, 1, which.max) # modify data of each model estimation accordingly for (i in seq_len(k)) { ml[[i]]$data <- ml[[i]]$data[i == split_obs,] # Drop id column in default case. The user did not supply id and therefore # does not expect the model data to include it. Data is ensured to have 'x' # as name of lifetime characteristic column data <- data[c("x", "status")] if (drop_id) ml[[i]]$data <- ml[[i]]$data[c("x", "status")] } names(ml) <- sprintf("mod_%i", 1:k) em_results <- list( a_priori = mix_est$priori, a_posteriori = mix_est$posteriori, groups = split_obs, logL = logL_complete, aic = aic_complete, bic = bic_complete ) class(em_results) <- c("wt_em_results", class(em_results)) ml$em_results <- em_results class(ml) <- c("wt_model", "wt_mixmod_em", class(ml)) ml } #' @export print.wt_mixmod_em <- function(x, digits = max(3L, getOption("digits") - 3L), ... ) { cat("Mixmod EM:\n") mods <- x[-length(x)] purrr::walk2(mods, seq_along(mods), function(model_estimation, i) { cat(paste0("Subgroup ", i, ":\n")) indent_by(print(model_estimation), 2) }) print(x[[length(x)]]) } #' @export print.wt_em_results <- function(x, digits = max(3L, getOption("digits") - 3L), ... ) { cat("EM Results:\n") indent_by({ cat("A priori\n") cat(x$a_priori) }, 2) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/mixture_identification.R
#' ML Estimation for Parametric Lifetime Distributions #' #' @description #' This function estimates the parameters of a parametric lifetime distribution #' for complete and (multiple) right-censored data. The parameters #' are determined in the frequently used (log-)location-scale parameterization. #' #' For the Weibull, estimates are additionally transformed such that they are in #' line with the parameterization provided by the *stats* package #' (see [Weibull][stats::Weibull]). #' #' @details #' Within `ml_estimation`, [optim][stats::optim] is called with `method = "BFGS"` #' and `control$fnscale = -1` to estimate the parameters that maximize the #' log-likelihood (see [loglik_function]). For threshold models, the profile #' log-likelihood is maximized in advance (see [loglik_profiling]). Once the #' threshold parameter is determined, the threshold model is treated like a #' distribution without threshold (lifetime is reduced by threshold estimate) #' and the general optimization routine is applied. #' #' Normal approximation confidence intervals for the parameters are computed as well. #' #' @param x A `tibble` with class `wt_reliability_data` returned by [reliability_data]. #' @param distribution Supposed distribution of the random variable. #' @param wts Optional vector of case weights. The length of `wts` must be equal #' to the number of observations in `x`. #' @param conf_level Confidence level of the interval. #' @param start_dist_params Optional vector with initial values of the #' (log-)location-scale parameters. #' @param control A list of control parameters (see 'Details' and #' [optim][stats::optim]). #' @template dots #' #' @template return-ml-estimation #' @templateVar data A `tibble` with class `wt_reliability_data` returned by #' [reliability_data]. #' #' @encoding UTF-8 #' #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' ## Data for two-parametric model: #' data_2p <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' ## Data for three-parametric model: #' data_3p <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Example 1 - Fitting a two-parametric weibull distribution: #' ml_2p <- ml_estimation( #' data_2p, #' distribution = "weibull" #' ) #' #' # Example 2 - Fitting a three-parametric lognormal distribution: #' ml_3p <- ml_estimation( #' data_3p, #' distribution = "lognormal3", #' conf_level = 0.99 #' ) #' #' @md #' #' @export ml_estimation <- function(x, ...) { UseMethod("ml_estimation") } #' @rdname ml_estimation #' #' @export ml_estimation.wt_reliability_data <- function(x, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), wts = rep(1, nrow(x)), conf_level = 0.95, start_dist_params = NULL, control = list(), ... ) { distribution <- match.arg(distribution) ml_estimation_( x, distribution = distribution, wts = wts, conf_level = conf_level, start_dist_params = start_dist_params, control = control ) } #' ML Estimation for Parametric Lifetime Distributions #' #' @inherit ml_estimation description details references #' #' @inheritParams ml_estimation #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param status A vector of binary data (0 or 1) indicating whether a unit is #' a right censored observation (= 0) or a failure (= 1). #' #' @template return-ml-estimation #' @templateVar data A `tibble` with columns `x` and `status`. #' #' @seealso [ml_estimation] #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' status_1 <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' #' cycles <- alloy$cycles #' status_2 <- alloy$status #' #' # Example 1 - Fitting a two-parametric weibull distribution: #' ml <- ml_estimation( #' x = obs, #' status = status_1, #' distribution = "weibull", #' conf_level = 0.90 #' ) #' #' # Example 2 - Fitting a three-parametric lognormal distribution: #' ml_2 <- ml_estimation( #' x = cycles, #' status = status_2, #' distribution = "lognormal3" #' ) #' #' @md #' #' @export ml_estimation.default <- function(x, status, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), wts = rep(1, length(x)), conf_level = 0.95, start_dist_params = NULL, control = list(), ... ) { distribution <- match.arg(distribution) data <- tibble::tibble(x = x, status = status) ml_estimation_( data = data, distribution = distribution, wts = wts, conf_level = conf_level, start_dist_params = start_dist_params, control = control ) } # Function that performs the parameter estimation: ml_estimation_ <- function(data, distribution, wts, conf_level, start_dist_params, # initial parameter vector control # control of optims control argument ) { # Prepare function inputs: x <- x_origin <- data$x # Used to compute the hessian for threshold models: status <- data$status ## Set initial values: if (purrr::is_null(start_dist_params)) { ### Vector of length 1 (scale) or 2 (location-scale) parameter(s): start_dist_params <- start_params( x = x, status = status, distribution = distribution ) ### Add 'NA' for general handling of 'start_dist_params' (length 2 or 3): start_dist_params <- c(start_dist_params, NA_real_) } else { check_dist_params(start_dist_params, distribution) if (length(start_dist_params) == 1L) { ### Add 'NA' in case of 'exponential' distribution to ensure length 2: start_dist_params <- c(start_dist_params, NA_real_) } } ## Number of parameters, could be either 2 or 3: n_par <- length(start_dist_params) # Pre-Step: Threshold models must be profiled w.r.t threshold: if (has_thres(distribution)) { ## Define upper bound for constraint optimization: ### For 'exponential2' gamma is smaller or equal to t_min: upper <- min(x[status == 1]) ### For other threshold distributions gamma is smaller than t_min: if (distribution != "exponential2") { upper <- (1 - (1 / 1e+5)) * upper } ## Initial value for threshold parameter: t0 <- start_dist_params[n_par] %NA% 0 ## Optimization of `loglik_profiling_()`: opt_thres <- stats::optim( par = t0, fn = loglik_profiling_, method = "L-BFGS-B", lower = 0, upper = upper, control = list(fnscale = -1), # no user input for profiling! hessian = FALSE, x = x, status = status, wts = wts, distribution = distribution ) opt_thres <- opt_thres$par ## Preparation for ML: x <- x - opt_thres } # Step 1: Estimation of one or two-parametric model (x or x - thres) using ML: ## Preparation: ### 'n_par' is 2 or 3 and must be reduced by 1L: n_par <- n_par - 1L ### Remove 'NA' or t0 since the latter (if exists) is included (x - opt_thres): start_dist_params <- start_dist_params[1:n_par] ### Force maximization: control$fnscale <- -1 ### Use log scale (sigma is the last element of 'start_dist_params'): start_dist_params[n_par] <- log(start_dist_params[n_par]) ## Optimization of one or two-parametric model: ml <- stats::optim( par = start_dist_params, fn = loglik_function_, method = "BFGS", control = control, hessian = TRUE, x = x, status = status, wts = wts, distribution = distribution, log_scale = TRUE ) ## Parameters: dist_params <- ml$par ## Names: if (n_par == 1L) { names_par <- "sigma" } else { names_par <- c("mu", "sigma") } ### Determine the hessian matrix for threshold distributions: if (exists("opt_thres", inherits = FALSE)) { #### Concatenate parameters: dist_params <- c(dist_params, opt_thres) names_par[n_par + 1] <- "gamma" #### Compute hessian w.r.t to 'dist_params' and original 'x': ml$hessian <- stats::optimHess( par = dist_params, fn = loglik_function_, control = control, x = x_origin, status = status, wts = wts, distribution = distribution, log_scale = TRUE ) } ## Set parameter names: names(dist_params) <- names_par ## Value of the log-likelihood at optimum: logL <- ml$value ## Variance-covariance matrix on log scale which is the inverse of the hessian: dist_varcov_logsigma <- solve(-ml$hessian) ## scale parameter on original scale: dist_params[n_par] <- exp(dist_params[n_par]) ## Transformation to obtain variance-covariance matrix on original scale: trans_mat <- diag(length(dist_params)) diag(trans_mat)[n_par] <- dist_params[n_par] dist_varcov <- trans_mat %*% dist_varcov_logsigma %*% trans_mat colnames(dist_varcov) <- rownames(dist_varcov) <- names(dist_params) # Step 2: Normal approximation confidence intervals: confint <- conf_normal_approx( dist_params = dist_params, dist_varcov = dist_varcov, conf_level = conf_level ) # Step 3: Form output: ## Alternative parameters and confidence intervals for Weibull: l_wb <- list() ## Weibull distribution; providing shape-scale coefficients and confint: if (distribution %in% c("weibull", "weibull3")) { estimates <- to_shape_scale_params(dist_params) conf_int <- to_shape_scale_confint(confint) l_wb <- list( shape_scale_coefficients = estimates, shape_scale_confint = conf_int ) } ## Exponential distribution; renaming 'sigma' with 'theta': if (std_parametric(distribution) == "exponential") { names(dist_params)[1] <- rownames(confint)[1] <- "theta" rownames(dist_varcov)[1] <- colnames(dist_varcov)[1] <- "theta" } n <- length(x_origin) # sample size k <- length(dist_params) # number of parameters ml_output <- c( list( coefficients = dist_params, confint = confint ), l_wb, # Empty, if not Weibull! list( varcov = dist_varcov, logL = logL, aic = -2 * logL + 2 * k, bic = -2 * logL + log(n) * k ) ) ml_output$data <- data ml_output$distribution <- distribution class(ml_output) <- c( "wt_model", "wt_ml_estimation", "wt_model_estimation", class(ml_output) ) ml_output } #' @export print.wt_ml_estimation <- function(x, digits = max(3L, getOption("digits") - 3L), ... ) { cat("Maximum Likelihood Estimation\n") NextMethod("print") }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/ml_estimation.R
# Function that returns starting values for log-likelihood optimization: start_params <- function(x, status, distribution ) { # Probability estimation method w.r.t status: method <- if(all(status == 1)) { "mr" } else { "kaplan" } # Probability estimation using midpoints for probabilities: pp <- estimate_cdf( x = x, status = status, method = method ) %>% dplyr::filter(.data$status == 1) x_init <- pp$x y_init <- 0.5 * (c(0, dplyr::lag(pp$prob)[-1]) + pp$prob) # Initial parameters, i.e. RR parameters: rr <- lm_( x = x_init, y = y_init, distribution = distribution ) rr$coefficients } # Normal approximation confidence intervals for parameters: conf_normal_approx <- function(dist_params, dist_varcov, conf_level ) { # Standard errors: dist_se <- sqrt(diag(dist_varcov)) # Normal confidence intervals: p_conf <- c((1 - conf_level), (1 + conf_level)) / 2 q_n <- stats::qnorm(p = p_conf) # Compute confidence intervals: ## Scale parameter is part of all distributions: w <- exp(q_n[2] * dist_se[["sigma"]] / dist_params[["sigma"]]) conf_sigma <- dist_params[["sigma"]] * c(1 / w, w) ## Location parameter is not present if distribution is 'exponential': if ("mu" %in% names(dist_params)) { conf_mu <- dist_params[["mu"]] + q_n * dist_se[["mu"]] } else { conf_mu <- NULL } ## Threshold parameter: if ("gamma" %in% names(dist_params)) { conf_gamma <- dist_params[["gamma"]] + q_n * dist_se[["gamma"]] } else { conf_gamma <- NULL } # Form confidence interval matrix: conf_int <- matrix(c(conf_mu, conf_sigma, conf_gamma), byrow = TRUE, ncol = 2) colnames(conf_int) <- paste(p_conf * 100, "%") rownames(conf_int) <- names(dist_params) # Return confidence interval: conf_int }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/ml_estimation_helpers.R
#' @export print.wt_model <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { NextMethod("print") } #' @export print.wt_model_estimation <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat("Coefficients:\n") print(format(stats::coef(x), digits = digits), print.gap = 2L, quote = FALSE) invisible(x) } #' @export print.wt_model_estimation_list <- function(x, digits = max( 3L, getOption("digits") - 3L ), ... ) { cat(paste("List of", length(x), "model estimations:\n")) purrr::walk2(x, names(x), function(model_estimation, method) { print(model_estimation) cat(paste("Method of CDF Estimation:", method, "\n")) cat("\n") }) invisible(x) } #' @export vcov.wt_model_estimation <- function(object, ...) { if (hasName(object, "varcov")) { object$varcov } else { stop( "Variance-covariance matrix of location-scale parameters does not exist!", call. = FALSE ) } } indent_by <- function(expr, n) { out <- utils::capture.output(expr) cat(paste(strrep(" ", n), out, "\n"), "\n") }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/model_estimation.R
#' Layout of the Probability Plot #' #' @description #' This function is used to create the layout of a probability plot. It is #' called inside of [plot_prob] to determine the appearance of the grid with #' respect to the given characteristic `x`. #' #' @param x A numeric vector which consists of lifetime data. `x` is used to #' specify the grid of the plot. #' @param y Optional argument. If used, it is a numeric vector which consists of #' failure probabilities with respect to `x`. #' @param distribution Supposed distribution of the random variable. #' @param title_main A character string which is assigned to the main title. #' @param title_x A character string which is assigned to the title of the x axis. #' @param title_y A character string which is assigned to the title of the y axis. #' @param plot_method Package, which is used for generating the plot output. #' #' @return A plot object containing the layout of the probability plot. #' #' @md #' #' @keywords internal plot_layout <- function(x, y = NULL, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", plot_method = c("plotly", "ggplot2") ) { distribution <- match.arg(distribution) plot_method <- match.arg(plot_method) # Call to `plot_layout_helper()` to determine the grid: layout_helper <- plot_layout_helper( x = x, y = y, distribution = distribution ) # Prepare inputs for S3 plot_layout_vis: x_list <- layout_helper[c("x_ticks", "x_labels")] y_list <- layout_helper[c("y_ticks", "y_labels")] p_obj <- if (plot_method == "plotly") { plotly::plotly_empty(type = "scatter", mode = "markers", colors = "Set2") } else { ggplot2::ggplot() } # Construct plot_method dependent grid: plot_layout_vis( p_obj = p_obj, x = x_list, y = y_list, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y ) } #' Probability Plotting Method for Univariate Lifetime Distributions #' #' @description #' This function is used to apply the graphical technique of probability #' plotting. It is either applied to the output of [estimate_cdf] #' (`plot_prob.wt_cdf_estimation`) or to the output of a mixture model from #' [mixmod_regression] / [mixmod_em] (`plot_prob.wt_model`). Note that in the #' latter case no distribution has to be specified because it is inferred from #' the model. #' #' @details #' If `x` was split by [mixmod_em], [estimate_cdf] with method `"johnson"` is #' applied to subgroup-specific data. The calculated plotting positions are #' shaped according to the determined split in [mixmod_em]. #' #' In [mixmod_regression] a maximum of three subgroups can be determined and thus #' being plotted. The intention of this function is to give the user a hint for #' the existence of a mixture model. An in-depth analysis should be done afterwards. #' #' For `plot_method == "plotly"` the marker label for x and y are determined by #' the first word provided in the argument `title_x` and `title_y` respectively, #' i.e. if `title_x = "Mileage in km"` the x label of the marker is "Mileage". #' The name of the legend entry is a combination of the `title_trace` and the #' number of determined subgroups (if any). If `title_trace = "Group"` and the #' data has been split in two groups, the legend entries are "Group: 1" and #' "Group: 2". #' #' @param x A tibble with class `wt_cdf_estimation` returned by [estimate_cdf] #' or a list with class `wt_model` returned by [rank_regression], [ml_estimation], #' [mixmod_regression] or [mixmod_em]. #' @param distribution Supposed distribution of the random variable. #' @param title_main A character string which is assigned to the main title. #' @param title_x A character string which is assigned to the title of the x axis. #' @param title_y A character string which is assigned to the title of the y axis. #' @param title_trace A character string which is assigned to the legend trace. #' @param plot_method Package, which is used for generating the plot output. #' @template dots #' #' @encoding UTF-8 #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @return A plot object containing the probability plot. #' #' @examples #' # Reliability data: #' data <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Probability estimation: #' prob_tbl <- estimate_cdf( #' data, #' methods = c("johnson", "kaplan") #' ) #' #' # Example 1 - Probability Plot Weibull: #' plot_weibull <- plot_prob(prob_tbl) #' #' # Example 2 - Probability Plot Lognormal: #' plot_lognormal <- plot_prob( #' x = prob_tbl, #' distribution = "lognormal" #' ) #' #' ## Mixture identification #' # Reliability data: #' data_mix <- reliability_data( #' voltage, #' x = hours, #' status = status #' ) #' #' prob_mix <- estimate_cdf( #' data_mix, #' methods = c("johnson", "kaplan") #' ) #' #' # Example 3 - Mixture identification using mixmod_regression: #' mix_mod_rr <- mixmod_regression(prob_mix) #' #' plot_mix_mod_rr <- plot_prob(x = mix_mod_rr) #' #' # Example 4 - Mixture identification using mixmod_em: #' mix_mod_em <- mixmod_em(data_mix) #' #' plot_mix_mod_em <- plot_prob(x = mix_mod_em) #' #' @md #' #' @export plot_prob <- function(x, ...) { UseMethod("plot_prob") } #' @rdname plot_prob #' #' @export plot_prob.wt_cdf_estimation <- function(x, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { distribution <- match.arg(distribution) plot_method <- match.arg(plot_method) plot_prob_( cdf_estimation = x, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' @rdname plot_prob #' #' @export plot_prob.wt_model <- function(x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { NextMethod() } #' @export plot_prob.wt_rank_regression <- function(x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { plot_method <- match.arg(plot_method) cdf_estimation <- x$data plot_prob.wt_cdf_estimation( x = cdf_estimation, distribution = std_parametric(x$distribution), title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' @export plot_prob.wt_ml_estimation <- function(x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { plot_method <- match.arg(plot_method) cdf_estimation <- estimate_cdf(x$data, methods = "johnson") plot_prob.wt_cdf_estimation( x = cdf_estimation, distribution = std_parametric(x$distribution), title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' @export plot_prob.wt_mixmod_regression <- function(x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { plot_method <- match.arg(plot_method) # Add variable 'group' to the data tibbles in each list: cdf_estimation <- purrr::map2_dfr( x, seq_along(x), function(model_estimation, i) { model_estimation$data %>% dplyr::mutate(group = as.character(i)) } ) # Segmentation inside `mixmod_regression()` is based on one distribution: distribution <- x[[1]]$distribution plot_prob.wt_cdf_estimation( x = cdf_estimation, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' @export plot_prob.wt_mixmod_em <- function(x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { plot_method <- match.arg(plot_method) # Remove last list element, i.e. 'em_results': model_estimation_list <- x[-length(x)] # Apply `estimate_cdf()` with `methods = "johnson"`: cdf_estimation <- purrr::map2_dfr( model_estimation_list, seq_along(model_estimation_list), function(model_estimation, index) { data <- reliability_data( model_estimation$data, x = "x", status = "status" ) cdf_estimation <- estimate_cdf(data, "johnson") cdf_estimation$cdf_estimation_method <- as.character(index) cdf_estimation } ) plot_prob.wt_cdf_estimation( x = cdf_estimation, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' @export plot_prob.wt_mixmod_regression_list <- function( x, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { plot_method <- match.arg(plot_method) # Add variable 'group' to the data tibbles in each list of each cdf estimation: cdf_estimation <- purrr::map_dfr( x, function(mixmod_regression) { purrr::map2_dfr( mixmod_regression, seq_along(mixmod_regression), function(model_estimation, index) { model_estimation$data %>% dplyr::mutate(group = as.character(index)) } ) } ) # Segmentation inside `mixmod_regression()` is based on one distribution: distribution <- x[[1]][[1]]$distribution plot_prob.wt_cdf_estimation( x = cdf_estimation, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' Probability Plotting Method for Univariate Lifetime Distributions #' #' @inherit plot_prob return references #' #' @description #' This function is used to apply the graphical technique of probability #' plotting. #' #' @details #' For `plot_method == "plotly"` the marker label for x and y are determined by #' the first word provided in the argument `title_x` and `title_y` respectively, #' i.e. if `title_x = "Mileage in km"` the x label of the marker is "Mileage". #' #' @inheritParams plot_prob #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, e.g. #' operating time (days/months in service), mileage (km, miles), load cycles. #' @param y A numeric vector which consists of estimated failure probabilities #' regarding the lifetime data in `x`. #' @param status A vector of binary data (0 or 1) indicating whether a unit is a #' right censored observation (= 0) or a failure (= 1). #' @param id Identification for every unit. #' #' @seealso [plot_prob] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Probability estimation: #' prob_tbl <- estimate_cdf( #' x = cycles, #' status = status, #' method = "johnson" #' ) #' #' # Example 1: Probability Plot Weibull: #' plot_weibull <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id #' ) #' #' # Example 2: Probability Plot Lognormal: #' plot_lognormal <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id, #' distribution = "lognormal" #' ) #' #' @md #' #' @export plot_prob.default <- function(x, y, status, id = rep("XXXXXX", length(x)), distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { distribution <- match.arg(distribution) plot_method <- match.arg(plot_method) # Fake cdf_estimation: cdf_estimation <- tibble::tibble( x = x, prob = y, status = status, id = id, cdf_estimation_method = NA_character_ ) plot_prob_( cdf_estimation = cdf_estimation, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } # Function that determines the positions and performs the plot method dispatch: plot_prob_ <- function(cdf_estimation, distribution, title_main, title_x, title_y, title_trace, plot_method ) { # Call to helper function: tbl_prob <- plot_prob_helper(cdf_estimation, distribution) # Call to `plot_layout()` to determine the distribution-specific grid: p_obj <- plot_layout( x = tbl_prob$x, y = tbl_prob$prob, # experimental! distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, plot_method = plot_method ) # Dispatch based on 'plot_method': p_obj <- plot_prob_vis( p_obj = p_obj, tbl_prob = tbl_prob, distribution = distribution, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace ) # Store distribution for compatibility checks: attr(p_obj, "distribution") <- distribution p_obj } #' Probability Plot for Separated Mixture Models #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `plot_prob_mix()` is no longer under active development, switching to #' [plot_prob] is recommended. #' #' @details #' This function is used to apply the graphical technique of probability #' plotting to univariate mixture models that have been separated with functions #' [mixmod_regression] or [mixmod_em]. #' #' If data has been split by `mixmod_em` the function `johnson_method` is applied #' to subgroup-specific data. The calculated plotting positions are shaped #' regarding the obtained split of the used splitting function. #' #' In [mixmod_regression] a maximum of three subgroups can be determined and thus #' being plotted. The intention of this function is to give the user a hint for #' the existence of a mixture model. An in-depth analysis should be done #' afterwards. #' #' The marker label for x and y are determined by the first word provided in the #' argument `title_x` and `title_y` respectively, i.e. if #' `title_x = "Mileage in km"` the x label of the marker is "Mileage". #' #' The name of the legend entry is a combination of the `title_trace` and the #' number of determined subgroups (if any). If `title_trace = "Group"` and the #' data has been split in two groups, the legend entries are "Group: 1" and #' "Group: 2". #' #' @encoding UTF-8 #' @references Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by #' Failure Mode, Quality Progress, 35(6), 47-52, 2002 #' #' @inheritParams plot_prob.default #' @param mix_output A list returned by [mixmod_regression] or [mixmod_em], which #' consists of values necessary to visualize the subgroups.The default value of #' `mix_output` is `NULL`. #' #' @seealso [plot_prob] #' #' @examples #' # Vectors: #' hours <- voltage$hours #' status <- voltage$status #' #' # Example 1 - Using result of mixmod_em: #' mix_mod_em <- mixmod_em( #' x = hours, #' status = status #' ) #' #' plot_weibull_em <- plot_prob_mix( #' x = hours, #' status = status, #' distribution = "weibull", #' mix_output = mix_mod_em #' ) #' #' # Example 2 - Using result of mixmod_regression: #' john <- estimate_cdf( #' x = hours, #' status = status, #' method = "johnson" #' ) #' #' mix_mod_reg <- mixmod_regression( #' x = john$x, #' y = john$prob, #' status = john$status, #' distribution = "weibull" #' ) #' #' plot_weibull_reg <- plot_prob_mix( #' x = hours, #' status = status, #' distribution = "weibull", #' mix_output = mix_mod_reg #' ) #' #' @md #' #' @export plot_prob_mix <- function( x, status, id = rep("XXXXXX", length(x)), distribution = c("weibull", "lognormal", "loglogistic"), mix_output, title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", plot_method = c("plotly", "ggplot2"), ... ) { deprecate_soft( "2.0.0", "plot_prob_mix()", "plot_prob()" ) plot_method <- match.arg(plot_method) plot_prob( mix_output, title_main = title_main, title_x = title_x, title_y = title_y, title_trace = title_trace, plot_method = plot_method ) } #' Add Estimated Population Line(s) to a Probability Plot #' #' @description #' This function adds one or multiple estimated regression lines to an existing #' probability plot ([plot_prob]). Depending on the output of the functions #' [rank_regression], [ml_estimation], [mixmod_regression] or [mixmod_em] one or #' multiple lines are plotted. #' #' @details #' The name of the legend entry is a combination of the `title_trace` and the #' number of determined subgroups from [mixmod_regression] or [mixmod_em]. If #' `title_trace = "Line"` and the data could be split in two groups, the legend #' entries would be "Line: 1" and "Line: 2". #' #' @inheritParams plot_prob.wt_cdf_estimation #' @param p_obj A plot object returned by [plot_prob]. #' @param x A list with class `wt_model` returned by [rank_regression], #' [ml_estimation], [mixmod_regression] or [mixmod_em]. #' #' @encoding UTF-8 #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @return A plot object containing the probability plot with plotting positions #' and the estimated regression line(s). #' #' @examples #' # Reliability data: #' data <- reliability_data(data = alloy, x = cycles, status = status) #' #' # Probability estimation: #' prob_tbl <- estimate_cdf(data, methods = c("johnson", "kaplan")) #' #' #' ## Rank Regression #' # Example 1 - Probability Plot and Regression Line Three-Parameter-Weibull: #' plot_weibull <- plot_prob(prob_tbl, distribution = "weibull") #' rr_weibull <- rank_regression(prob_tbl, distribution = "weibull3") #' #' plot_reg_weibull <- plot_mod(p_obj = plot_weibull, x = rr_weibull) #' #' # Example 2 - Probability Plot and Regression Line Three-Parameter-Lognormal: #' plot_lognormal <- plot_prob(prob_tbl, distribution = "lognormal") #' rr_lognormal <- rank_regression(prob_tbl, distribution = "lognormal3") #' #' plot_reg_lognormal <- plot_mod(p_obj = plot_lognormal, x = rr_lognormal) #' #' #' ## ML Estimation #' # Example 3 - Probability Plot and Regression Line Two-Parameter-Weibull: #' plot_weibull <- plot_prob(prob_tbl, distribution = "weibull") #' ml_weibull_2 <- ml_estimation(data, distribution = "weibull") #' #' plot_reg_weibull_2 <- plot_mod(p_obj = plot_weibull, ml_weibull_2) #' #' #' ## Mixture Identification #' # Reliability data: #' data_mix <- reliability_data(voltage, x = hours, status = status) #' #' # Probability estimation: #' prob_mix <- estimate_cdf( #' data_mix, #' methods = c("johnson", "kaplan", "nelson") #' ) #' #' # Example 4 - Probability Plot and Regression Line Mixmod Regression: #' mix_mod_rr <- mixmod_regression(prob_mix, distribution = "weibull") #' plot_weibull <- plot_prob(mix_mod_rr) #' #' plot_reg_mix_mod_rr <- plot_mod(p_obj = plot_weibull, x = mix_mod_rr) #' #' # Example 5 - Probability Plot and Regression Line Mixmod EM: #' mix_mod_em <- mixmod_em(data_mix) #' plot_weibull <- plot_prob(mix_mod_em) #' #' plot_reg_mix_mod_em <- plot_mod(p_obj = plot_weibull, x = mix_mod_em) #' #' @md #' #' @export plot_mod <- function(p_obj, x, ...) { UseMethod("plot_mod", x) } #' @rdname plot_mod #' #' @export plot_mod.wt_model <- function(p_obj, x, title_trace = "Fit", ... ) { NextMethod("plot_mod", x) } #' @export plot_mod.wt_model_estimation <- function(p_obj, x, title_trace = "Fit", ... ) { check_compatible_distributions( attr(p_obj, "distribution"), x$distribution ) failed_data <- dplyr::filter(x$data, .data$status == 1) plot_mod.default( p_obj = p_obj, x = range(failed_data$x), dist_params = x$coefficients, distribution = x$distribution, title_trace = title_trace ) } #' @export plot_mod.wt_model_estimation_list <- function(p_obj, x, title_trace = "Fit", ... ) { cdf_estimation_methods <- names(x) tbl_mod <- purrr::map2_dfr( x, cdf_estimation_methods, function(model_estimation, cdf_estimation_method) { check_compatible_distributions( attr(p_obj, "distribution"), model_estimation$distribution ) failed_data <- dplyr::filter(model_estimation$data, .data$status == 1) plot_mod_helper( x = range(failed_data$x), dist_params = model_estimation$coefficients, distribution = model_estimation$distribution, cdf_estimation_method = cdf_estimation_method ) } ) plot_mod_vis( p_obj = p_obj, tbl_mod = tbl_mod, title_trace = title_trace ) } #' @export plot_mod.wt_mixmod_regression <- function(p_obj, x, title_trace = "Fit", ... ) { tbl_mod <- purrr::map2_dfr( x, seq_along(x), function(model_estimation, index) { check_compatible_distributions( attr(p_obj, "distribution"), model_estimation$distribution ) # Extract cdf_estimation_method from model_estimation cdf_estimation_method <- if ( !tibble::has_name(model_estimation$data, "cdf_estimation_method") ) { # Case mixmod_em (plot_mod.mixmod_em calls this method internally) as.character(index) } else { # Case mixmod_regression model_estimation$data$cdf_estimation_method[1] } plot_mod_mix_helper( model_estimation = model_estimation, cdf_estimation_method = cdf_estimation_method, group = as.character(index) ) } ) plot_mod_vis( p_obj = p_obj, tbl_mod = tbl_mod, title_trace = title_trace ) } #' @export plot_mod.wt_mixmod_regression_list <- function(p_obj, x, title_trace = "Fit", ... ) { tbl_mod <- purrr::map2_dfr( x, names(x), function(mixmod_regression, cdf_estimation_method) { purrr::map2_dfr( mixmod_regression, seq_along(mixmod_regression), function(model_estimation, index) { check_compatible_distributions( attr(p_obj, "distribution"), model_estimation$distribution ) plot_mod_mix_helper( model_estimation = model_estimation, cdf_estimation_method = cdf_estimation_method, group = as.character(index) ) } ) } ) plot_mod_vis( p_obj = p_obj, tbl_mod = tbl_mod, title_trace = title_trace ) } #' @export plot_mod.wt_mixmod_em <- function(p_obj, x, title_trace = "Fit", ... ) { # Remove em results to get model_estimation_list model_estimation_list <- x[-length(x)] plot_mod.wt_mixmod_regression( p_obj = p_obj, x = model_estimation_list, title_trace = title_trace ) } #' Add Estimated Population Line to a Probability Plot #' #' @description #' This function adds an estimated regression line to an existing probability #' plot ([plot_prob]). #' #' @inherit plot_mod references #' #' @inheritParams plot_mod #' @inheritParams plot_prob.default #' @param x A numeric vector containing the x-coordinates of the respective #' regression line. #' @param dist_params A (named) numeric vector of estimated location and scale #' parameters for a specified distribution. The order of elements is important. #' First entry needs to be the location parameter \eqn{\mu} and the second #' element needs to be the scale parameter \eqn{\sigma}. If a three-parametric #' model is used the third element is the threshold parameter \eqn{\gamma}. #' #' @return A plot object containing the probability plot with plotting positions #' and the estimated regression line. #' #' @seealso [plot_mod] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Probability estimation #' prob_tbl <- estimate_cdf(x = cycles, status = status, method = "johnson") #' #' # Example 1: Probability Plot and Regression Line Three-Parameter-Weibull: #' plot_weibull <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id, #' distribution = "weibull" #' ) #' #' rr <- rank_regression( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' distribution = "weibull3" #' ) #' #' plot_reg_weibull <- plot_mod( #' p_obj = plot_weibull, #' x = prob_tbl$x, #' dist_params = rr$coefficients, #' distribution = "weibull3" #' ) #' #' #' #' # Example 2: Probability Plot and Regression Line Three-Parameter-Lognormal: #' plot_lognormal <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id, #' distribution = "lognormal" #' ) #' #' rr_ln <- rank_regression( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' distribution = "lognormal3" #' ) #' #' plot_reg_lognormal <- plot_mod( #' p_obj = plot_lognormal, #' x = prob_tbl$x, #' dist_params = rr_ln$coefficients, #' distribution = "lognormal3" #' ) #' #' ## Mixture Identification #' # Vectors: #' hours <- voltage$hours #' status <- voltage$status #' #' # Probability estimation: #' prob_mix <- estimate_cdf( #' x = hours, #' status = status, #' method = "johnson" #' ) #' #' @md #' #' @export plot_mod.default <- function(p_obj, x, dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), title_trace = "Fit", ... ) { distribution <- match.arg(distribution) check_compatible_distributions( attr(p_obj, "distribution"), distribution ) tbl_mod <- plot_mod_helper( x, dist_params, distribution ) plot_mod_vis( p_obj = p_obj, tbl_mod = tbl_mod, title_trace = title_trace ) } #' Add Estimated Population Lines of a Separated Mixture Model to a #' Probability Plot #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `plot_mod_mix()` is no longer under active development, switching to #' [plot_mod] is recommended. #' #' @details #' This function adds one or multiple estimated regression lines to an existing #' probability plot [plot_prob]). Depending on the output of the function #' [mixmod_regression] or [mixmod_em] one or multiple lines are plotted. #' #' The name of the legend entry is a combination of the `title_trace` and the #' number of determined subgroups. If `title_trace = "Line"` and the data has #' been split in two groups, the legend entries would be `"Line: 1"` and #' `"Line: 2"`. #' #' @encoding UTF-8 #' @references Doganaksoy, N.; Hahn, G.; Meeker, W. Q., Reliability Analysis by #' Failure Mode, Quality Progress, 35(6), 47-52, 2002 #' #' @inheritParams plot_mod.default #' @inheritParams plot_prob.default #' @param p_obj A plot object returned by [plot_prob_mix]. #' @param mix_output A list returned by [mixmod_regression] or [mixmod_em], #' which consists of elements necessary to visualize the regression lines. #' #' @return A plot object containing the probability plot with plotting positions #' and estimated regression line(s). #' #' @examples #' # Vectors: #' hours <- voltage$hours #' status <- voltage$status #' #' # Example 1 - Using result of mixmod_em in mix_output: #' mix_mod_em <- mixmod_em( #' x = hours, #' status = status, #' distribution = "weibull", #' conf_level = 0.95, #' k = 2, #' method = "EM", #' n_iter = 150 #' ) #' #' plot_weibull_em <- plot_prob_mix( #' x = hours, #' status = status, #' id = id, #' distribution = "weibull", #' mix_output = mix_mod_em #' ) #' #' plot_weibull_emlines <- plot_mod_mix( #' p_obj = plot_weibull_em, #' x = hours, #' status = status, #' mix_output = mix_mod_em, #' distribution = "weibull" #' ) #' #' # Example 2 - Using result of mixmod_regression in mix_output: #' john <- johnson_method(x = hours, status = status) #' mix_mod_reg <- mixmod_regression( #' x = john$x, #' y = john$prob, #' status = john$status, #' distribution = "weibull" #' ) #' #' plot_weibull_reg <- plot_prob_mix( #' x = john$x, #' status = john$status, #' id = john$id, #' distribution = "weibull", #' mix_output = mix_mod_reg, #' ) #' #' plot_weibull_reglines <- plot_mod_mix( #' p_obj = plot_weibull_reg, #' x = john$x, #' status = john$status, #' mix_output = mix_mod_reg, #' distribution = "weibull" #' ) #' #' @md #' #' @export plot_mod_mix <- function(p_obj, x, status, mix_output, distribution = c( "weibull", "lognormal", "loglogistic" ), title_trace = "Fit", ... ) { deprecate_soft( "2.0.0", "plot_mod_mix()", "plot_mod()" ) plot_mod( p_obj = p_obj, x = mix_output, title_trace = title_trace ) } #' Add Confidence Region(s) for Quantiles and Probabilities #' #' This function is used to add estimated confidence region(s) to an existing #' probability plot. Since confidence regions are related to the estimated #' regression line, the latter is provided as well. #' #' @param p_obj A plot object returned by [plot_prob]. #' @param x A tibble with class `wt_confint` returned by [confint_betabinom] or #' [confint_fisher]. #' @param title_trace_mod A character string which is assigned to the model trace #' in the legend. #' @param title_trace_conf A character string which is assigned to the confidence #' trace in the legend. #' @template dots #' #' @encoding UTF-8 #' @references Meeker, William Q; Escobar, Luis A., Statistical methods for #' reliability data, New York: Wiley series in probability and statistics, 1998 #' #' @return A plot object containing the probability plot with plotting positions, #' the estimated regression line and the estimated confidence region(s). #' #' @examples #' # Reliability data: #' data <- reliability_data(data = alloy, x = cycles, status = status) #' #' # Probability estimation: #' prob_tbl <- estimate_cdf(data, methods = "johnson") #' #' # Example 1 - Probability Plot, Regression Line and Confidence Bounds for Three-Parameter-Weibull: #' rr <- rank_regression(prob_tbl, distribution = "weibull3") #' #' conf_betabin <- confint_betabinom(rr) #' #' plot_weibull <- plot_prob(prob_tbl, distribution = "weibull") #' #' plot_conf_beta <- plot_conf( #' p_obj = plot_weibull, #' x = conf_betabin #' ) #' #' # Example 2 - Probability Plot, Regression Line and Confidence Bounds for Three-Parameter-Lognormal: #' rr_ln <- rank_regression( #' prob_tbl, #' distribution = "lognormal3", #' conf_level = 0.9 #' ) #' #' conf_betabin_ln <- confint_betabinom( #' rr_ln, #' bounds = "two_sided", #' conf_level = 0.9, #' direction = "y" #' ) #' #' plot_lognormal <- plot_prob(prob_tbl, distribution = "lognormal") #' #' plot_conf_beta_ln <- plot_conf( #' p_obj = plot_lognormal, #' x = conf_betabin_ln #' ) #' #' # Example 3 - Probability Plot, Regression Line and Confidence Bounds for MLE #' ml <- ml_estimation(data, distribution = "weibull") #' #' conf_fisher <- confint_fisher(ml) #' #' plot_weibull <- plot_prob(prob_tbl, distribution = "weibull") #' #' plot_conf_fisher_weibull <- plot_conf( #' p_obj = plot_weibull, #' x = conf_fisher #' ) #' #' @md #' #' @export plot_conf <- function(p_obj, x, ...) { UseMethod("plot_conf", x) } #' @rdname plot_conf #' #' @export plot_conf.wt_confint <- function(p_obj, x, title_trace_mod = "Fit", title_trace_conf = "Confidence Limit", ... ) { # Extract models, could be either of class 'wt_model_estimation' or '*_list': mod <- attr(x, "model_estimation") # If-clause captures `ml_estimation()` or `rank_regression()` models, where # the latter was performed with only one 'cdf_estimation_method': if (inherits(mod, "wt_model_estimation")) { ## Fake a 'model_estimation_list': if (hasName(mod$data, "cdf_estimation_method")) { ### `rank_regression()` with only one 'cdf_estimation_method': cdf_estimation_method <- mod$data$cdf_estimation_method[1] } else { ### `ml_estimation()` where 'data' has no 'cdf_estimation_method' column: cdf_estimation_method <- NA_character_ } mod <- list(mod) names(mod) <- cdf_estimation_method } # Perform customized `plot_mod()` on 'model_estimation_list': cdf_estimation_methods <- names(mod) tbl_mod <- purrr::map2_dfr( mod, cdf_estimation_methods, function(model_estimation, cdf_estimation_method) { check_compatible_distributions( attr(p_obj, "distribution"), model_estimation$distribution ) if (!is.na(cdf_estimation_methods)) { # Case: confint_betabinom # Filter x by cdf_estimation_method, so that the corresponding x values # can be passed to the plot_mod_helper in the next step conf <- dplyr::filter( x, .data$cdf_estimation_method == !!cdf_estimation_method ) } else { # Case: confint_fisher conf <- x } plot_mod_helper( x = conf$x, # x coordinates of confint guarantees consideration of b lives. dist_params = model_estimation$coefficients, distribution = model_estimation$distribution, cdf_estimation_method = cdf_estimation_method ) } ) tbl_conf <- plot_conf_helper_2(confint = x) bounds <- attr(x, "bounds", exact = TRUE) # Same x coordinates for `plot_mod()` and `plot_conf()`: if (bounds == "two_sided") { tbl_mod$lower <- x$lower_bound tbl_mod$upper <- x$upper_bound } else if (bounds == "lower") { tbl_mod$lower <- x$lower_bound } else { tbl_mod$upper <- x$upper_bound } p_mod <- plot_mod_vis( p_obj = p_obj, tbl_mod = tbl_mod, title_trace = title_trace_mod ) plot_conf_vis( p_mod, tbl_conf, title_trace_conf ) } #' Add Confidence Region(s) for Quantiles and Probabilities #' #' @inherit plot_conf return references #' #' @description #' This function is used to add estimated confidence region(s) to an existing #' probability plot which also includes the estimated regression line. #' #' @details #' It is important that the length of the vectors provided as lists in `x` and #' `y` match with the length of the vectors `x` and `y` in the function [plot_mod]. #' For this reason the following procedure is recommended: #' #' * Calculate confidence intervals with the function [confint_betabinom] or #' [confint_fisher] and store it in a `data.frame`. For instance call it df. #' * Inside [plot_mod] use the output `df$x` for `x` and `df$prob` for `y` of #' the function(s) named before. #' * In __Examples__ the described approach is shown with code. #' #' @inheritParams plot_prob.default #' @param p_obj A plot object returned by [plot_mod]. #' @param x A list containing the x-coordinates of the confidence region(s). The #' list can be of length 1 or 2. For more information see **Details**. #' @param y A list containing the y-coordinates of the Confidence Region(s). #' The list can be of length 1 or 2. For more information see **Details**. #' @param direction A character string specifying the direction of the plotted #' interval(s). `"y"` for failure probabilities or `"x"` for quantiles. #' #' @seealso [plot_conf] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' prob_tbl <- estimate_cdf(x = cycles, status = status, method = "johnson") #' #' # Example 1 - Probability Plot, Regression Line and Confidence Bounds for Three-Parameter-Weibull: #' rr <- rank_regression( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' distribution = "weibull3" #' ) #' #' conf_betabin <- confint_betabinom( #' x = prob_tbl$x, #' status = prob_tbl$status, #' dist_params = rr$coefficients, #' distribution = "weibull3" #' ) #' #' plot_weibull <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id, #' distribution = "weibull" #' ) #' #' plot_reg_weibull <- plot_mod( #' p_obj = plot_weibull, #' x = conf_betabin$x, #' y = conf_betabin$prob, #' dist_params = rr$coefficients, #' distribution = "weibull3" #' ) #' #' plot_conf_beta <- plot_conf( #' p_obj = plot_reg_weibull, #' x = list(conf_betabin$x), #' y = list(conf_betabin$lower_bound, conf_betabin$upper_bound), #' direction = "y", #' distribution = "weibull3" #' ) #' #' # Example 2 - Probability Plot, Regression Line and Confidence Bounds for Three-Parameter-Lognormal: #' rr_ln <- rank_regression( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' distribution = "lognormal3" #' ) #' #' conf_betabin_ln <- confint_betabinom( #' x = prob_tbl$x, #' status = prob_tbl$status, #' dist_params = rr_ln$coefficients, #' distribution = "lognormal3" #' ) #' #' plot_lognormal <- plot_prob( #' x = prob_tbl$x, #' y = prob_tbl$prob, #' status = prob_tbl$status, #' id = prob_tbl$id, #' distribution = "lognormal" #' ) #' #' plot_reg_lognormal <- plot_mod( #' p_obj = plot_lognormal, #' x = conf_betabin_ln$x, #' y = conf_betabin_ln$prob, #' dist_params = rr_ln$coefficients, #' distribution = "lognormal3" #' ) #' #' plot_conf_beta_ln <- plot_conf( #' p_obj = plot_reg_lognormal, #' x = list(conf_betabin_ln$x), #' y = list(conf_betabin_ln$lower_bound, conf_betabin_ln$upper_bound), #' direction = "y", #' distribution = "lognormal3" #' ) #' #' @md #' #' @export plot_conf.default <- function(p_obj, x, y, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), direction = c("y", "x"), title_trace = "Confidence Limit", ... ) { direction <- match.arg(direction) distribution <- match.arg(distribution) check_compatible_distributions( attr(p_obj, "distribution"), distribution ) # Extracting tbl_mod: plot_method <- if (inherits(p_obj, "plotly")) { "plotly" } else if (inherits(p_obj, "ggplot")) { "ggplot2" } else { stop( "'p_obj' must be either a {plotly} or {ggplot2} object!", call. = FALSE ) } tbl_mod <- if (plot_method == "plotly") { plotly::plotly_data(p_obj) } else { p_obj$layers[[2]]$data } tbl_conf <- plot_conf_helper( tbl_mod, x, y, direction, distribution ) plot_conf_vis( p_obj, tbl_conf, title_trace ) } #' Add Population Line(s) to an Existing Grid #' #' @description #' This function adds one (or multiple) linearized CDF(s) to an existing plot grid. #' #' @details #' `dist_params_tbl` is a `data.frame` with parameter columns. An overview of the #' distribution-specific parameters and their order can be found in section #' 'Distributions'. #' #' If only one population line should be displayed, a numeric vector is also #' supported. The order of the vector elements also corresponds to the table in #' section 'Distributions'. #' #' @inheritParams plot_prob #' @param p_obj A plot object to which the population line(s) is (are) added or #' `NULL`. If `NULL` the population line(s) is (are) plotted in an empty grid. #' @param x A numeric vector of length two or greater used for the x coordinates #' of the population line. If `length(x) == 2` a sequence of length 200 between #' `x[1]` and `x[2]` is created. This sequence is equidistant with respect to the #' scale of the x axis. If `length(x) > 2` the elements of `x` are the x #' coordinates of the population line. #' @param dist_params_tbl A `data.frame`. See 'Details'. #' @param distribution Supposed distribution of the random variable. The distinction #' between a threshold distribution and the respective standard variant is made with #' `dist_params_tbl`. #' @param tol The failure probability is restricted to the interval #' \eqn{[tol, 1 - tol]}. The default value is in accordance with the decimal #' places shown in the hover for `plot_method = "plotly"`. #' @param plot_method Package, which is used for generating the plot output. Only #' used when `p_obj = NULL`. If `p_obj != NULL` the plot object is used to #' determine the plot method. #' #' @return A plot object containing the linearized CDF(s). #' #' @template dist-params_tbl #' #' @examples #' x <- rweibull(n = 100, shape = 1, scale = 20000) #' #' # Example 1 - Two-parametric straight line: #' pop_weibull <- plot_pop( #' p_obj = NULL, #' x = range(x), #' dist_params_tbl = c(log(20000), 1), #' distribution = "weibull" #' ) #' #' # Example 2 - Three-parametric curved line: #' x2 <- rweibull(n = 100, shape = 1, scale = 20000) + 5000 #' #' pop_weibull_2 <- plot_pop( #' p_obj = NULL, #' x = x2, #' dist_params_tbl = c(log(20000 - 5000), 1, 5000), #' distribution = "weibull" #' ) #' #' # Example 3 - Multiple lines: #' pop_weibull_3 <- plot_pop( #' p_obj = NULL, #' x = x, #' dist_params_tbl = data.frame( #' p_1 = c(log(20000), log(20000), log(20000)), #' p_2 = c(1, 1.5, 2) #' ), #' distribution = "weibull", #' plot_method = "ggplot2" #' ) #' #' # Example 4 - Compare two- and three-parametric distributions: #' pop_weibull_4 <- plot_pop( #' p_obj = NULL, #' x = x, #' dist_params_tbl = data.frame( #' param_1 = c(log(20000), log(20000)), #' param_2 = c(1, 1), #' param_3 = c(NA, 2) #' ), #' distribution = "weibull" #' ) #' #' @md #' #' @export plot_pop <- function(p_obj = NULL, x, dist_params_tbl, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), tol = 1e-6, title_trace = "Population", plot_method = c("plotly", "ggplot2") ) { distribution <- match.arg(distribution) # Check if plot object is provided: if (purrr::is_null(p_obj)) { plot_method <- match.arg(plot_method) p_obj <- plot_layout( x = x, distribution = distribution, plot_method = plot_method ) } # `dist_params_tbl` should be a data.frame with columns loc, sc, thres: ## Check for threshold distribution: if (is_std_parametric(distribution, dist_params_tbl)) { ### thres must be set even if distribution has no threshold: thres <- NA_real_ } else { ### Extract `thres` as a vector with `[[`: thres <- dist_params_tbl[[length(dist_params_tbl)]] } ## Support vector instead of tibble for ease of use in dist_params_tbl: if (!inherits(dist_params_tbl, "data.frame")) { dist_params_tbl <- as.data.frame(t(dist_params_tbl)) } ## Special case w.r.t the order of parameters for "exponential": if (distribution == "exponential") { ### Add never existing parameter column 'loc': dist_params_tbl <- dplyr::bind_cols(loc = NA_real_, dist_params_tbl) } ## Set or overwrite the threshold column: dist_params_tbl[3] <- thres ## Ensure correct naming: names(dist_params_tbl) <- c("loc", "sc", "thres") # Call `plot_pop_helper()` for line points and labels: tbl_pop <- plot_pop_helper(x, dist_params_tbl, distribution, tol) # Call `plot_pop_vis.*` for the visualization: plot_pop_vis( p_obj, tbl_pop, title_trace ) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/plot_functions.R
plot_layout_vis <- function(p_obj, ...) { UseMethod("plot_layout_vis") } plot_prob_vis <- function(p_obj, ...) { UseMethod("plot_prob_vis") } plot_mod_vis <- function(p_obj, ...) { UseMethod("plot_mod_vis") } plot_conf_vis <- function(p_obj, ...) { UseMethod("plot_conf_vis") } plot_pop_vis <- function(p_obj, ...) { UseMethod("plot_pop_vis") }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/plot_functions_generic.R
#' @export plot_layout_vis.ggplot <- function(p_obj, # An empty ggplot object. x, # Named list with x_ticks and x_labels. y, # Named list with y_ticks and y_labels. distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", ... ) { distribution <- match.arg(distribution) p_obj <- if (distribution %in% c("weibull", "lognormal", "loglogistic")) { p_obj + ggplot2::scale_x_log10( breaks = x$x_ticks, minor_breaks = NULL, labels = x$x_labels ) } else { p_obj + ggplot2::scale_x_continuous( breaks = ggplot2::waiver(), minor_breaks = NULL, labels = ggplot2::waiver() ) } p_obj <- p_obj + ggplot2::scale_y_continuous( breaks = y$y_ticks, minor_breaks = NULL, labels = y$y_labels, guide = ggplot2::guide_axis( # experimental! check.overlap = TRUE ) ) + ggplot2::theme_bw() + ggplot2::theme( # Rotate x axis labels: axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust = 1), # Center title: plot.title = ggplot2::element_text(hjust = 0.5) ) + ggplot2::labs(title = title_main, x = title_x, y = title_y) p_obj } #' @export plot_prob_vis.ggplot <- function(p_obj, tbl_prob, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", ... ) { distribution <- match.arg(distribution) n_method <- length(unique(tbl_prob$cdf_estimation_method)) n_group <- length(unique(tbl_prob[["group"]])) if (n_method == 1) tbl_prob$cdf_estimation_method <- "" if (n_group <= 1) tbl_prob$group <- "" mapping <- if (n_group <= 1) { if (n_method == 1) { ggplot2::aes(x = .data$x, y = .data$q, color = I("#3C8DBC")) } else { ggplot2::aes(x = .data$x, y = .data$q, color = .data$cdf_estimation_method) } } else { if (n_method == 1) { ggplot2::aes( x = .data$x, y = .data$q, color = .data$group ) } else { ggplot2::aes( x = .data$x, y = .data$q, color = .data$cdf_estimation_method, shape = .data$group ) } } labs <- if (n_group <= 1 || n_method == 1) { ggplot2::labs(color = title_trace) } else { ggplot2::labs(color = title_trace, shape = "Subgroups") } p_prob <- p_obj + ggplot2::geom_point( data = tbl_prob, mapping = mapping ) + labs p_prob } #' @export plot_mod_vis.ggplot <- function(p_obj, tbl_mod, title_trace = "Fit", ... ) { n_method <- length(unique(tbl_mod$cdf_estimation_method)) n_group <- length(unique(tbl_mod$group)) if (n_method == 1) tbl_mod$cdf_estimation_method <- "" mapping <- if (n_group == 1) { if (n_method == 1) { ggplot2::aes( x = .data$x_p, y = .data$q, color = I("#CC2222") ) } else { ggplot2::aes( x = .data$x_p, y = .data$q, color = .data$cdf_estimation_method ) } } else { # group aesthetic must be paste of method and group to create distinct # groups if (n_method == 1) { ggplot2::aes( x = .data$x_p, y = .data$q, color = .data$group ) } else { ggplot2::aes( x = .data$x_p, y = .data$q, color = .data$cdf_estimation_method, group = paste(.data$cdf_estimation_method, .data$group) ) } } p_mod <- p_obj + ggplot2::geom_line( data = tbl_mod, mapping = mapping ) + ggplot2::labs( color = paste(p_obj$labels$colour, "+\n", title_trace) ) p_mod } #' @export plot_conf_vis.ggplot <- function(p_obj, tbl_p, title_trace, ... ) { n_method <- length(unique(tbl_p$cdf_estimation_method)) mapping <- if (all(is.na(tbl_p$cdf_estimation_method)) || n_method == 1) { ggplot2::aes( x = .data$x, y = .data$q, group = .data$bound, color = I("#CC2222") ) } else { ggplot2::aes( x = .data$x, y = .data$q, group = paste(.data$bound, .data$cdf_estimation_method), color = .data$cdf_estimation_method ) } p_conf <- p_obj + ggplot2::geom_line( data = tbl_p, mapping = mapping, linetype = "CC" ) + ggplot2::labs( color = paste(p_obj$labels$colour, "+\n", title_trace) ) p_conf } #' @export plot_pop_vis.ggplot <- function(p_obj, tbl_pop, title_trace, ... ) { tbl_pop <- tbl_pop %>% dplyr::mutate( name = purrr::map2_chr(.data$param_val, .data$param_label, to_name_pop) ) p_pop <- p_obj + ggplot2::geom_line( data = tbl_pop, mapping = ggplot2::aes(x = .data$x_s, y = .data$q, color = .data$name) ) + ggplot2::labs(color = title_trace) p_pop }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/plot_functions_ggplot2.R
#' @export plot_layout_vis.plotly <- function(p_obj, # An empty plotly object. x, # Named list with x_ticks and x_labels. y, # Named list with y_ticks and y_labels. distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", ... ) { distribution <- match.arg(distribution) # Configuration of x axis: x_config <- list( title = list( text = title_x ), autorange = TRUE, rangemode = "nonnegative", ticks = "inside", tickwidth = 1, tickfont = list(family = 'Arial', size = 10), #tickmode = "array", tickangle = 90, showticklabels = TRUE, zeroline = FALSE, showgrid = TRUE, gridwidth = 1, exponentformat = "none", showline = TRUE, linecolor = "#a0a0a0" ) ## Distributions that need a log transformed x axis: if (distribution %in% c("weibull", "lognormal", "loglogistic")) { x_config <- c( x_config, list( type = "log", tickvals = x$x_ticks, ticktext = x$x_labels ) ) } # Configuration y axis: ## Adjust y values for exponential distribution (no overlapping): if (distribution != "exponential") { y_tickvals <- y$y_ticks y_ticktext <- y$y_labels } else { ### Smarter values for exponential: y_labs <- c(.01, .1, .2, .3, .5, .6, .7, .8, .9, .95, .99, .999, .9999, .99999) * 100 ind <- y$y_labels %in% y_labs y_tickvals <- y$y_ticks[ind] y_ticktext <- y$y_labels[ind] } y_config <- list( title = list( text = title_y ), autorange = TRUE, tickvals = y_tickvals, ticktext = y_ticktext, ticks = "inside", tickwidth = 1, tickfont = list(family = 'Arial', size = 10), showticklabels = TRUE, zeroline = FALSE, showgrid = TRUE, gridwidth = 1, exponentformat = "none", showline = TRUE, linecolor = "#a0a0a0" ) # Configuration of legend: l <- list( title = list( font = list( family = "Arial", size = 10, color = "#000000" ) ) ) # Layout margins: m <- list( l = 55, r = 10, b = 55, t = 25, pad = 4 ) title <- list( text = title_main, font = list( family = "Arial", size = 16, color = "#000000" ) ) # Create grid: p_obj <- p_obj %>% plotly::layout( title = title, separators = ".", legend = l, xaxis = x_config, yaxis = y_config, margin = m ) p_obj } #' @export plot_prob_vis.plotly <- function(p_obj, tbl_prob, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "exponential" ), title_main = "Probability Plot", title_x = "Characteristic", title_y = "Unreliability", title_trace = "Sample", ... ) { distribution <- match.arg(distribution) mark_x <- unlist(strsplit(title_x, " "))[1] mark_y <- unlist(strsplit(title_y, " "))[1] # Suppress warning by subsetting with character: n_group <- length(unique(tbl_prob[["group"]])) n_method <- length(unique(tbl_prob$cdf_estimation_method)) color <- if (n_method == 1) I("#3C8DBC") else ~cdf_estimation_method symbol <- if (n_group == 0) NULL else ~group name <- to_name(tbl_prob, n_method, n_group, title_trace) # Construct probability plot: p_prob <- p_obj %>% plotly::add_trace( data = tbl_prob, x = ~x, y = ~q, type = "scatter", mode = "markers", hoverinfo = "text", name = name, color = color, colors = "Set2", symbol = symbol, legendgroup = ~cdf_estimation_method, text = paste( "ID:", tbl_prob$id, paste("<br>", paste0(mark_x, ":")), format(tbl_prob$x, digits = 3), paste("<br>", paste0(mark_y, ":")), format(tbl_prob$prob, digits = 6) ) ) %>% plotly::layout(showlegend = TRUE) p_prob } #' @export plot_mod_vis.plotly <- function(p_obj, tbl_mod, title_trace = "Fit", ... ) { x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1] y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1] n_method <- length(unique(tbl_mod$cdf_estimation_method)) n_group <- length(unique(tbl_mod$group)) color <- if (n_method == 1) I("#CC2222") else ~cdf_estimation_method ## Creation of hovertext arg_list <- list( x = tbl_mod$x_p, y = tbl_mod$y_p, param_val = tbl_mod$param_val, param_label = tbl_mod$param_label ) # tbl_mod has names lower / upper if set in plot_conf() if (hasName(tbl_mod, "lower")) { arg_list$lower <- tbl_mod$lower } if (hasName(tbl_mod, "upper")) { arg_list$upper <- tbl_mod$upper } tbl_mod <- tbl_mod %>% dplyr::mutate( hovertext = purrr::pmap_chr( arg_list, hovertext_mod, x_mark = x_mark, y_mark = y_mark ) ) # Reminder: Splitting the line by group happens by using the name name <- to_name(tbl_mod, n_method, n_group, title_trace) p_mod <- plotly::add_lines( p = p_obj, data = tbl_mod, x = ~x_p, y = ~q, type = "scatter", mode = "lines", hoverinfo = "text", name = name, color = color, colors = "Set2", legendgroup = ~cdf_estimation_method, text = ~hovertext ) p_mod } #' @export plot_conf_vis.plotly <- function(p_obj, tbl_p, title_trace, ... ) { # Get axis labels in hover: x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1] y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1] n_method <- length(unique(tbl_p$cdf_estimation_method)) color <- if (n_method == 1) I("#CC2222") else ~cdf_estimation_method name <- to_name(tbl_p, n_method, n_group = 0, title_trace) p_conf <- plotly::add_lines( p = p_obj, # tbl_p is grouped by bound. Therefore two separate lines are drawn # for two-sided confidence intervals data = tbl_p, x = ~x, y = ~q, type = "scatter", mode = "lines", # hoverinfo text is set in plot_mod hoverinfo = "skip", line = list(dash = "dash", width = 1), color = color, colors = "Set2", name = name, legendgroup = ~cdf_estimation_method ) p_conf } #' @export plot_pop_vis.plotly <- function(p_obj, tbl_pop, title_trace, ... ) { # Get axis labels in hover x_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$xaxis$title$text, " "))[1] y_mark <- unlist(strsplit(p_obj$x$layoutAttrs[[2]]$yaxis$title$text, " "))[1] # Hovertext and name tbl_pop <- tbl_pop %>% dplyr::mutate( hovertext = purrr::pmap_chr( list( x = .data$x_s, y = .data$y_s, param_val = .data$param_val, param_label = .data$param_label ), hovertext_mod, x_mark = x_mark, y_mark = y_mark ), name = purrr::map2_chr(.data$param_val, .data$param_label, to_name_pop) ) p_pop <- plotly::add_lines( p = p_obj, data = tbl_pop, x = ~x_s, y = ~q, type = "scatter", mode = "lines", hoverinfo = "text", # color = ~group, colors = "Set2", name = ~name, line = list(width = 1), text = ~hovertext ) %>% plotly::layout( showlegend = TRUE, legend = list( title = list( text = title_trace ) ) ) p_pop } # Hover text for plot_mod() and plot_conf(): hovertext_mod <- function(x, y, param_val, param_label, x_mark, y_mark, lower = NULL, upper = NULL ) { not_na <- !is.na(param_val) x_text <- paste0(x_mark, ": ", format(x, digits = 3)) y_text <- paste0(y_mark, ": ", format(y, digits = 3)) lower_text <- if (!is.null(lower)) paste("Lower Bound:", format(lower, digits = 3)) upper_text <- if (!is.null(upper)) paste("Upper Bound:", format(upper, digits = 3)) param_text <- paste(param_label[not_na], param_val[not_na], collapse = ", ") do.call( paste, c( # Drop NULLs, otherwise paste will add one <br> per NULL purrr::compact( list( x_text, y_text, lower_text, upper_text, param_text ) ), sep = "<br>" ) ) } # Trace name for plot_pop(): to_name_pop <- function(param_val, param_label ) { not_na <- !is.na(param_val) paste(param_label[not_na], param_val[not_na], collapse = ", ") } # Trace name for plot_prob(), plot_mod() and plot_conf(): to_name <- function(tbl, n_method, n_group, title_trace ) { if (n_method <= 1) { if (n_group <= 1) { title_trace } else { paste0(title_trace, ": ", tbl$group) } } else { if (n_group <= 1) { paste0(title_trace, ": ", tbl$cdf_estimation_method) } else { paste0(title_trace, ": ", tbl$cdf_estimation_method, ", ", tbl$group) } } }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/plot_functions_plotly.R
# Helper function to set the distribution-specific grid: plot_layout_helper <- function(x, y = NULL, distribution ) { # Define x-ticks as logarithm to the base of 10 for log-location-scale distributions: if (distribution %in% c("weibull", "lognormal", "loglogistic")) { # Layout depends on x, using a function to build helpful sequences: x_base <- function(xb) floor(log10(xb)) xlog10_range <- (x_base(min(x)) - 1):x_base(max(x)) # x-ticks and x-labels: x_ticks <- sapply( xlog10_range, function(z) seq(10 ^ z, 10 ^ (z + 1), 10 ^ z), simplify = TRUE ) x_ticks <- round(as.numeric(x_ticks), digits = 10) x_ticks <- x_ticks[!duplicated(x_ticks)] x_labels <- x_ticks x_labels[c(rep(F, 3), rep(T, 6))] <- " " } else { # We don't need these values, therefore we return NULL: x_ticks <- x_labels <- NULL } # y-ticks and y-labels: ## Hard coded but it's okay since range is always between 0 and 1: y_s <- c(.0000001, .000001, .00001, .0001, .001, .005, .01, .05, .1, .2, .3, .5, .6, .7, .8, .9, .95, .99, .999, .9999, .99999) ## If argument y is not `NULL` y is used to narrow down the range of y_s: if (!purrr::is_null(y)) { ### y range: ymin <- min(y, na.rm = TRUE) ymax <- max(y, na.rm = TRUE) ### Determine adjacent indices, i.e. min(y)_(i-1) and max(y)_(i+1) if exist: ind_min <- max(which(y_s < ymin), 1L) ind_max <- min(which(y_s > ymax), length(y_s)) y_s <- y_s[ind_min:ind_max] } y_ticks <- q_std(y_s, distribution) y_labels <- y_s * 100 # Plot: l <- list( x_ticks = x_ticks, x_labels = x_labels, y_ticks = y_ticks, y_labels = y_labels ) l } # Helper function to compute the distribution-specific plotting positions: plot_prob_helper <- function(tbl, distribution ) { tbl <- tbl %>% dplyr::filter(.data$status == 1) %>% dplyr::arrange(.data$x) tbl$q <- q_std(tbl$prob, distribution) tbl } # Helper function to compute distribution-specific points of the regression line: plot_mod_helper <- function(x, dist_params, distribution, cdf_estimation_method = NA_character_ ) { if (length(x) == 2) { if (std_parametric(distribution) %in% c("weibull", "lognormal", "loglogistic")) { x_p <- 10 ^ seq(log10(x[1]), log10(x[2]), length.out = 100) } else { x_p <- seq(x[1], x[2], length.out = 100) } } if (length(x) > 2) { if ( length(x) < 30 && distribution %in% c("weibull3", "lognormal3", "loglogistic3") ) { warning( "'x' has less than 30 values and distribution is three-parametric. Consider using 'x = range(x)' to avoid visual kinks in regression line. ", call. = FALSE ) } x_p <- x } y_p <- predict_prob( q = x_p, dist_params = dist_params, distribution = distribution ) tbl_pred <- tibble::tibble(x_p = x_p, y_p = y_p) q <- q_std(y_p, std_parametric(distribution)) # Preparation of plotly hovers: n_par <- length(dist_params) ## Values: param_val <- rep(NA_character_, 3) param_val[1:n_par] <- format(dist_params, digits = 3) ## Labels: ### Enforce length 3: if (std_parametric(distribution) == "exponential") { param_label <- c("\u03B8:", NA_character_, NA_character_) } else { param_label <- c("\u03BC:", "\u03C3:", NA_character_) } if (has_thres(distribution)) { param_label[n_par] <- "\u03B3:" } tbl_pred <- tbl_pred %>% dplyr::mutate( param_val = list(param_val), param_label = list(param_label), cdf_estimation_method = cdf_estimation_method, group = NA_character_, q = q ) } # Helper function to compute distribution-specific points of the regression line: plot_mod_mix_helper <- function(model_estimation, cdf_estimation_method, group ) { distribution <- model_estimation$distribution data <- model_estimation$data %>% dplyr::filter(.data$status == 1) x_min <- min(data$x, na.rm = TRUE) x_max <- max(data$x, na.rm = TRUE) x_p <- seq(x_min, x_max, length.out = 200) y_p <- predict_prob( q = x_p, dist_params = model_estimation$coefficients, distribution = distribution ) param_1 <- format(model_estimation$coefficients[[1]], digits = 3) param_2 <- format(model_estimation$coefficients[[2]], digits = 3) label_1 <- "\u03BC:" label_2 <- "\u03C3:" tbl_p <- tibble::tibble( x_p = x_p, y_p = y_p, param_val = list(c(param_1, param_2)), param_label = list(c(label_1, label_2)), cdf_estimation_method = cdf_estimation_method, group = group ) tbl_p$q <- q_std(tbl_p$y_p, distribution) tbl_p } # Helper function for S3 method plot_conf.wt_confint: plot_conf_helper_2 <- function(confint) { direction <- attr(confint, "direction", exact = TRUE) distribution <- attr(confint, "distribution", exact = TRUE) tbl_upper <- if (hasName(confint, "upper_bound")) { if (direction == "x") { tibble::tibble( x = confint$upper_bound, y = confint$prob, bound = "Upper", cdf_estimation_method = confint$cdf_estimation_method ) } else { tibble::tibble( x = confint$x, y = confint$upper_bound, bound = "Upper", cdf_estimation_method = confint$cdf_estimation_method ) } } tbl_lower <- if (hasName(confint, "lower_bound")) { if (direction == "x") { tibble::tibble( x = confint$lower_bound, y = confint$prob, bound = "Lower", cdf_estimation_method = confint$cdf_estimation_method ) } else { tibble::tibble( x = confint$x, y = confint$lower_bound, bound = "Lower", cdf_estimation_method = confint$cdf_estimation_method ) } } tbl_p <- dplyr::bind_rows(tbl_upper, tbl_lower) tbl_p$q <- q_std(tbl_p$y, std_parametric(distribution)) tbl_p <- dplyr::group_by(tbl_p, .data$bound) tbl_p } # Helper function for S3 method plot_conf.default: plot_conf_helper <- function(tbl_mod, x, y, direction, distribution ) { # Construct x, y from x/y, upper/lower bounds (depending on direction and bounds) lst <- Map(tibble::tibble, x = x, y = y) tbl_p <- dplyr::bind_rows(lst, .id = "bound") if (direction == "y") { tbl_p$bound <- ifelse(test = tbl_p$y < tbl_mod$y_p, yes = "Lower", no = "Upper") } else { tbl_p$bound <- ifelse(test = tbl_p$x < tbl_mod$x_p, yes = "Lower", no = "Upper") } tbl_p$q <- q_std(tbl_p$y, std_parametric(distribution)) tbl_p <- dplyr::group_by(tbl_p, .data$bound) tbl_p$cdf_estimation_method <- NA_character_ tbl_p } # Helper function for `plot_pop()`: plot_pop_helper <- function(x, dist_params_tbl, distribution, tol = 1e-6 ) { # Determine equidistant x positions if needed: x_s <- if (length(x) == 2) { 10 ^ seq(log10(x[1]), log10(x[2]), length.out = 200) } else { x } # Set groups, since every row is its own distribution: tbl_pop <- dist_params_tbl %>% dplyr::mutate(group = as.character(dplyr::row_number())) # Map predict_prob over tbl_pop: tbl_pop <- purrr::pmap_dfr( tbl_pop, x_s = x_s, distribution = distribution, function(loc = NA, sc, thres = NA, group, x_s, distribution) { # Replace NA with NULL, so that loc and thres are ignored in c(): dist_params <- c(loc %NA% NULL, sc, thres %NA% NULL) if (!is_std_parametric(distribution, dist_params)) { # Threshold models: distribution <- paste0(distribution, length(dist_params)) } tibble::tibble( loc = loc, sc = sc, thres = thres, group = group, x_s = x_s, y_s = predict_prob( q = x_s, dist_params = dist_params, distribution = distribution ) ) } ) tbl_pop <- tbl_pop %>% dplyr::filter(.data$y_s < 1, .data$y_s > 0) tbl_pop$q <- q_std(tbl_pop$y_s, distribution) # Set values and labels for plotlys hoverinfo: tbl_pop <- tbl_pop %>% dplyr::mutate( param_val_1 = ifelse(is.na(.data$loc), NA, format(.data$loc, digits = 3)), param_val_2 = format(.data$sc, digits = 3), param_val_3 = ifelse(is.na(.data$thres), NA, format(.data$thres, digits = 3)), param_label_1 = ifelse(is.na(.data$loc), NA, "\u03BC:"), param_label_2 = if (distribution == "exponential") "\u03B8:" else "\u03C3:", param_label_3 = ifelse(is.na(.data$thres), NA, "\u03B3:") ) %>% dplyr::rowwise() %>% dplyr::mutate( param_val = list( c(.data$param_val_1, .data$param_val_2, .data$param_val_3) ), param_label = list( c(.data$param_label_1, .data$param_label_2, .data$param_label_3) ) ) %>% dplyr::ungroup() %>% dplyr::select("x_s", "y_s", "q", "param_val", "param_label", "group") %>% dplyr::filter(.data$y_s <= 1 - tol, .data$y_s >= tol) tbl_pop }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/plot_helpers.R
#' Prediction of Quantiles for Parametric Lifetime Distributions #' #' @description #' This function predicts the quantiles of a parametric lifetime distribution #' using the (log-)location-scale parameterization. #' #' @details #' For a given set of parameters and specified probabilities the quantiles #' of the chosen model are determined. #' #' @param p A numeric vector of probabilities. #' @param dist_params A vector of parameters. An overview of the #' distribution-specific parameters can be found in section 'Distributions'. #' @param distribution Supposed distribution of the random variable. #' #' @return A vector with predicted quantiles. #' #' @template dist-params #' #' @examples #' # Example 1 - Predicted quantiles for a two-parameter weibull distribution: #' quants_weib2 <- predict_quantile( #' p = c(0.01, 0.1, 0.5), #' dist_params = c(5, 0.5), #' distribution = "weibull" #' ) #' #' # Example 2 - Predicted quantiles for a three-parameter weibull distribution: #' quants_weib3 <- predict_quantile( #' p = c(0.01, 0.1, 0.5), #' dist_params = c(5, 0.5, 10), #' distribution = "weibull3" #' ) #' #' @md #' #' @export predict_quantile <- function(p, dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ) ) { distribution <- match.arg(distribution) check_dist_params(dist_params, distribution) n_par <- length(dist_params) # Determine q_p by switching between distributions: q_p <- switch( std_parametric(distribution), "weibull" = , "sev" = qsev(p) * dist_params[[2]] + dist_params[[1]], "lognormal" = , "normal" = stats::qnorm(p) * dist_params[[2]] + dist_params[[1]], "loglogistic" = , "logistic" = stats::qlogis(p) * dist_params[[2]] + dist_params[[1]], "exponential" = stats::qexp(p) * dist_params[[1]] ) if (std_parametric(distribution) %in% c("weibull", "lognormal", "loglogistic")) { q_p <- exp(q_p) } # Threshold models: if (has_thres(distribution)) { q_p <- q_p + dist_params[[n_par]] } q_p } #' Prediction of Failure Probabilities for Parametric Lifetime Distributions #' #' @description #' This function predicts the (failure) probabilities of a parametric lifetime #' distribution using the (log-)location-scale parameterization. #' #' @details #' For a given set of parameters and specified quantiles the probabilities #' of the chosen model are determined. #' #' @inheritParams predict_quantile #' @param q A numeric vector of quantiles. #' #' @return A vector with predicted (failure) probabilities. #' #' @template dist-params #' #' @examples #' # Example 1 - Predicted probabilities for a two-parameter weibull distribution: #' probs_weib2 <- predict_prob( #' q = c(15, 48, 124), #' dist_params = c(5, 0.5), #' distribution = "weibull" #' ) #' #' # Example 2 - Predicted quantiles for a three-parameter weibull distribution: #' probs_weib3 <- predict_prob( #' q = c(25, 58, 134), #' dist_params = c(5, 0.5, 10), #' distribution = "weibull3" #' ) #' #' @md #' #' @export predict_prob <- function(q, dist_params, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3","lognormal3", "loglogistic3", "exponential", "exponential2" ) ) { distribution <- match.arg(distribution) check_dist_params(dist_params, distribution) # Standardize: z <- standardize( x = q, dist_params = dist_params, distribution = distribution ) distribution <- std_parametric(distribution) # Determine p_q by switching between distributions: p_q <- p_std(z, distribution) p_q }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/predict.R
#' Estimation of Failure Probabilities #' #' @description #' This function applies a non-parametric method to estimate the failure #' probabilities of complete data taking (multiple) right-censored observations #' into account. #' #' @template details-estimate-cdf #' @templateVar header One or multiple techniques can be used for the `methods` argument: #' #' @param x A tibble with class `wt_reliability_data` returned by [reliability_data]. #' @param methods One or multiple methods of `"mr"`, `"johnson"`, `"kaplan"` or #' `"nelson"` used for the estimation of failure probabilities. See 'Details'. #' @param options A list of named options. See 'Options'. #' @template dots #' #' @return A tibble with class `wt_cdf_estimation` containing the following columns: #' #' * `id` : Identification for every unit. #' * `x` : Lifetime characteristic. #' * `status` : Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' * `rank` : The (computed) ranks. Determined for methods `"mr"` and `"johnson"`, #' filled with `NA` for other methods or if `status = 0`. #' * `prob` : Estimated failure probabilities, `NA` if `status = 0`. #' * `cdf_estimation_method` : Specified method for the estimation of failure #' probabilities. #' #' @section Options: #' Argument `options` is a named list of options: #' #' | Method | Name | Value | #' | --------- | ---------------- | ----------------------------------------- | #' | `mr` | `mr_method` | `"benard"` (default) or `"invbeta"` | #' | `mr` | `mr_ties.method` | `"max"` (default), `"min"` or `"average"` | #' | `johnson` | `johnson_method` | `"benard"` (default) or `"invbeta"` | #' #' @references *NIST/SEMATECH e-Handbook of Statistical Methods*, #' *8.2.1.5. Empirical model fitting - distribution free (Kaplan-Meier) approach*, #' [NIST SEMATECH](https://www.itl.nist.gov/div898/handbook/apr/section2/apr215.htm), #' December 3, 2020 #' #' @examples #' # Reliability data: #' data <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Example 1 - Johnson method: #' prob_tbl <- estimate_cdf( #' x = data, #' methods = "johnson" #' ) #' #' # Example 2 - Multiple methods: #' prob_tbl_2 <- estimate_cdf( #' x = data, #' methods = c("johnson", "kaplan", "nelson") #' ) #' #' # Example 3 - Method 'mr' with options: #' prob_tbl_3 <- estimate_cdf( #' x = data, #' methods = "mr", #' options = list( #' mr_method = "invbeta", #' mr_ties.method = "average" #' ) #' ) #' #' # Example 4 - Multiple methods and options: #' prob_tbl_4 <- estimate_cdf( #' x = data, #' methods = c("mr", "johnson"), #' options = list( #' mr_ties.method = "max", #' johnson_method = "invbeta" #' ) #' ) #' #' @md #' #' @export estimate_cdf <- function(x, ...) { UseMethod("estimate_cdf") } #' @rdname estimate_cdf #' #' @export estimate_cdf.wt_reliability_data <- function(x, methods = c( "mr", "johnson", "kaplan", "nelson" ), options = list(), ... ) { methods <- if (missing(methods)) { "mr" } else { unique(match.arg(methods, several.ok = TRUE)) } tbl_out <- purrr::map_dfr(methods, function(method) { if (method == "mr") { mr_method_( data = x, method = options$mr_method %||% "benard", ties.method = options$mr_ties.method %||% "max" ) } else if (method == "johnson") { johnson_method_( data = x, method = options$johnson_method %||% "benard" ) } else { switch( method, "kaplan" = kaplan_method_(data = x), "nelson" = nelson_method_(data = x) ) } }) class(tbl_out) <- c("wt_cdf_estimation", class(tbl_out)) return(tbl_out) } #' Estimation of Failure Probabilities #' #' @inherit estimate_cdf description return references #' #' @template details-estimate-cdf #' @templateVar header The following techniques can be used for the `method` argument: #' #' @inheritParams estimate_cdf #' @param x A numeric vector which consists of lifetime data. Lifetime #' data could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param status A vector of binary data (0 or 1) indicating whether unit *i* #' is a right censored observation (= 0) or a failure (= 1). #' @param id A vector for the identification of every unit. Default is `NULL`. #' @param method Method used for the estimation of failure probabilities. See #' 'Details'. #' #' @inheritSection estimate_cdf Options #' #' @seealso [estimate_cdf] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Example 1 - Johnson method: #' prob_tbl <- estimate_cdf( #' x = cycles, #' status = status, #' method = "johnson" #' ) #' #' #' # Example 2 - Method 'mr' with options: #' prob_tbl_2 <- estimate_cdf( #' x = cycles, #' status = status, #' method = "mr", #' options = list( #' mr_method = "invbeta", #' mr_ties.method = "average" #' ) #' ) #' #' @md #' #' @export estimate_cdf.default <- function(x, status, id = NULL, method = c( "mr", "johnson", "kaplan", "nelson" ), options = list(), ... ) { # Fail early, if user tries to call estimate_cdf.wt_reliability_data with a # tibble which is not of class reliability data. Otherwise failure would occur # in reliability_data, which is counterintuitive status data <- reliability_data(x = x, status = status, id = id) method <- match.arg(method) estimate_cdf.wt_reliability_data( x = data, methods = method, options = options ) } #' @export print.wt_cdf_estimation <- function(x, ...) { n_methods <- length(unique(x$cdf_estimation_method)) if (n_methods == 1) { cat( "CDF estimation for method '", x$cdf_estimation_method[1], "':\n", sep = "" ) } else { cat( "CDF estimation for methods ", paste0("'", unique(x$cdf_estimation_method), "'", collapse = ", "), ":\n", sep = "" ) } NextMethod() } #' Estimation of Failure Probabilities using Median Ranks #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `mr_method()` is no longer under active development, switching to [estimate_cdf] #' is recommended. #' #' @details #' This non-parametric approach (*Median Ranks*) is used to estimate the #' failure probabilities in terms of complete data. Two methods are available to #' estimate the cumulative distribution function *F(t)*: #' #' * `"benard"` : Benard's approximation for Median Ranks. #' * `"invbeta"` : Exact Median Ranks using the inverse beta distribution. #' #' @inheritParams estimate_cdf.default #' @param status A vector of ones indicating that every unit has failed. #' @param method Method for the estimation of the cdf. Can be `"benard"` (default) #' or `"invbeta"`. #' @param ties.method A character string specifying how ties are treated, #' default is `"max"`. #' #' @return A tibble with only failed units containing the following columns: #' #' * `id` : Identification for every unit. #' * `x` : Lifetime characteristic. #' * `status` : Status of failed units (always 1). #' * `rank` : Assigned ranks. #' * `prob` : Estimated failure probabilities. #' * `cdf_estimation_method` : Specified method for the estimation of failure #' probabilities (always 'mr'). #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' state <- rep(1, length(obs)) #' uic <- c("3435", "1203", "958X", "XX71", "abcd", "tz46", #' "fl29", "AX23", "Uy12", "kl1a") #' #' # Example 1 - Benard's approximation: #' tbl_mr <- mr_method( #' x = obs, #' status = state, #' id = uic, #' method = "benard" #' ) #' #' # Example 2 - Inverse beta distribution: #' tbl_mr_invbeta <- mr_method( #' x = obs, #' status = state, #' method = "invbeta" #' ) #' #' @md #' #' @export mr_method <- function(x, status = rep(1, length(x)), id = NULL, method = c("benard", "invbeta"), ties.method = c("max", "min", "average") ) { deprecate_soft("2.0.0", "mr_method()", "estimate_cdf()") method <- match.arg(method) ties.method <- match.arg(ties.method) if (!purrr::is_null(id)) { if (!((length(x) == length(status)) && (length(x) == length(id)))) { stop("'x', 'status' and 'id' must be of same length!", call. = FALSE) } } else { if (length(x) != length(status)) { stop("'x' and 'status' must be of same length!", call. = FALSE) } } data <- reliability_data(x = x, status = status, id = id) mr_method_(data, method, ties.method) } mr_method_ <- function(data, method = "benard", ties.method = "max" ) { if (!all(data$status == 1)) { message("The 'mr' method only considers failed units (status == 1) and does", " not retain intact units (status == 0).") } tbl_in <- data %>% # Remove additional classes tibble::as_tibble() tbl_calc <- tbl_in %>% dplyr::filter(.data$status == 1) %>% dplyr::arrange(.data$x) %>% dplyr::mutate(rank = rank(.data$x, ties.method = ties.method)) if (method == "benard") { tbl_calc <- dplyr::mutate( tbl_calc, prob = (.data$rank - .3) / (length(.data$x) + .4) ) } else { tbl_calc <- dplyr::mutate( tbl_calc, prob = stats::qbeta(.5, .data$rank, length(.data$x) - .data$rank + 1) ) } tbl_out <- tbl_calc %>% dplyr::mutate(cdf_estimation_method = "mr") %>% dplyr::relocate( "id", "x", "status", "rank", "prob", "cdf_estimation_method" ) tbl_out } #' Estimation of Failure Probabilities using Johnson's Method #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `johnson_method()` is no longer under active development, switching to #' [estimate_cdf] is recommended. #' #' @details #' This non-parametric approach is used to estimate the failure probabilities in #' terms of uncensored or (multiple) right censored data. Compared to complete #' data the correction is done by calculating adjusted ranks which takes #' non-defective units into account. #' #' @inheritParams mr_method #' @param status A vector of binary data (0 or 1) indicating whether a unit is #' a right censored observation (= 0) or a failure (= 1). #' #' @return A tibble containing the following columns: #' #' * `id` : Identification for every unit. #' * `x` : Lifetime characteristic. #' * `status` : Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' * `rank` : Adjusted ranks, `NA` if `status = 0`. #' * `prob` : Estimated failure probabilities, `NA` if `status = 0`. #' * `cdf_estimation_method` : Specified method for the estimation of failure #' probabilities (always 'johnson'). #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' state <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' uic <- c("3435", "1203", "958X", "XX71", "abcd", "tz46", #' "fl29", "AX23", "Uy12", "kl1a") #' #' # Example 1 - Johnson method for intact and failed units: #' tbl_john <- johnson_method( #' x = obs, #' status = state, #' id = uic #' ) #' #' # Example 2 - Johnson's method works also if only defective units are considered: #' tbl_john_2 <- johnson_method( #' x = obs, #' status = rep(1, length(obs)) #' ) #' #' @md #' #' @export johnson_method <- function(x, status, id = NULL, method = c("benard", "invbeta") ) { deprecate_soft("2.0.0", "johnson_method()", "estimate_cdf()") method <- match.arg(method) if (!purrr::is_null(id)) { if (!((length(x) == length(status)) && (length(x) == length(id)))) { stop("'x', 'status' and 'id' must be of same length!", call. = FALSE) } } else { if (length(x) != length(status)) { stop("'x' and 'status' must be of same length!", call. = FALSE) } } data <- reliability_data(x = x, status = status, id = id) johnson_method_(data, method) } johnson_method_ <- function(data, method = "benard") { tbl_in <- data %>% # Remove additional classes tibble::as_tibble() tbl_calc <- tbl_in %>% dplyr::group_by(.data$x) %>% dplyr::mutate( failure = sum(.data$status == 1), survivor = sum(.data$status == 0) ) %>% dplyr::distinct(.data$x, .keep_all = TRUE) %>% dplyr::arrange(.data$x) %>% dplyr::ungroup() %>% dplyr::mutate( n_i = .data$failure + .data$survivor, n_out = dplyr::lag(cumsum(.data$n_i), n = 1L, default = 0) ) %>% dplyr::mutate( rank = calculate_ranks( f = .data$failure, n_out = .data$n_out, n = sum(.data$n_i) ) ) if (method == "benard") { tbl_calc <- dplyr::mutate( tbl_calc, prob = (.data$rank - .3) / (sum(.data$n_i) + .4) ) } else { tbl_calc <- dplyr::mutate( tbl_calc, prob = stats::qbeta(.5, .data$rank, sum(.data$n_i) - .data$rank + 1) ) } tbl_out <- tbl_in %>% dplyr::arrange(.data$x) %>% dplyr::mutate( rank = ifelse( .data$status == 1, tbl_calc$rank[match(.data$x[order(.data$x)], tbl_calc$x)], NA_real_ ), prob = ifelse( .data$status == 1, tbl_calc$prob[match(.data$x[order(.data$x)], tbl_calc$x)], NA_real_ ) ) %>% dplyr::mutate(cdf_estimation_method = "johnson") %>% dplyr::relocate( "id", "x", "status", "rank", "prob", "cdf_estimation_method" ) tbl_out } #' Estimation of Failure Probabilities using the Kaplan-Meier Estimator #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `kaplan_method()` is no longer under active development, switching to #' [estimate_cdf] is recommended. #' #' @details #' Whereas the non-parametric Kaplan-Meier estimator is used to estimate the #' survival function *S(t)* in terms of (multiple) right censored data, the #' complement is an estimate of the cumulative distribution function *F(t)*. #' One modification is made in contrast to the original Kaplan-Meier estimator #' (see 'References'). #' #' @inheritParams johnson_method #' #' @return A tibble containing the following columns: #' #' * `id` : Identification for every unit. #' * `x` : Lifetime characteristic. #' * `status` : Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' * `rank` : Filled with `NA`. #' * `prob` : Estimated failure probabilities, `NA` if `status = 0`. #' * `cdf_estimation_method` : Specified method for the estimation of failure #' probabilities (always 'kaplan'). #' #' @references *NIST/SEMATECH e-Handbook of Statistical Methods*, #' *8.2.1.5. Empirical model fitting - distribution free (Kaplan-Meier) approach*, #' [NIST SEMATECH](https://www.itl.nist.gov/div898/handbook/apr/section2/apr215.htm), #' December 3, 2020 #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' state <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' state_2 <- c(0, 1, 1, 0, 0, 0, 1, 0, 0, 1) #' uic <- c("3435", "1203", "958X", "XX71", "abcd", "tz46", #' "fl29", "AX23","Uy12", "kl1a") #' #' # Example 1 - Observation with highest characteristic is an intact unit: #' tbl_kap <- kaplan_method( #' x = obs, #' status = state, #' id = uic #' ) #' #' # Example 2 - Observation with highest characteristic is a defective unit: #' tbl_kap_2 <- kaplan_method( #' x = obs, #' status = state_2 #' ) #' #' @md #' #' @export kaplan_method <- function(x, status, id = NULL ) { deprecate_soft("2.0.0", "kaplan_method()", "estimate_cdf()") if (!purrr::is_null(id)) { if (!((length(x) == length(status)) && (length(x) == length(id)))) { stop("'x', 'status' and 'id' must be of same length!", call. = FALSE) } } else { if (length(x) != length(status)) { stop("'x' and 'status' must be of same length!", call. = FALSE) } } data <- reliability_data(x = x, status = status, id = id) kaplan_method_(data) } kaplan_method_ <- function(data) { if (all(data$status == 1)) { warning( 'Use methods = "mr" since there is no censored data problem!', call. = FALSE ) } tbl_in <- data %>% # Remove additional classes tibble::as_tibble() tbl_calc <- tbl_in %>% dplyr::group_by(.data$x) %>% dplyr::mutate( failure = sum(.data$status == 1), survivor = sum(.data$status == 0) ) %>% dplyr::distinct(.data$x, .keep_all = TRUE) %>% dplyr::arrange(.data$x) %>% dplyr::ungroup() %>% dplyr::mutate( n_i = .data$failure + .data$survivor, n_out = dplyr::lag(cumsum(.data$n_i), n = 1L, default = 0), n_in = sum(.data$n_i) - .data$n_out ) if (tbl_in$status[which.max(tbl_in$x)] == 0) { tbl_calc <- tbl_calc %>% dplyr::mutate( prob = 1 - cumprod((.data$n_in - .data$failure) / .data$n_in) ) } else { tbl_calc <- tbl_calc %>% dplyr::mutate( prob = 1 - (((.data$n_in + .7) / (.data$n_in + .4)) * cumprod( ((.data$n_in + .7) - .data$failure) / (.data$n_in + 1.7) ) ) ) } tbl_out <- tbl_in %>% dplyr::arrange(.data$x) %>% dplyr::mutate( rank = NA_real_, prob = ifelse( .data$status == 1, tbl_calc$prob[match(.data$x[order(.data$x)], tbl_calc$x)], NA_real_ ), cdf_estimation_method = "kaplan" ) %>% dplyr::relocate( "id", "x", "status", "rank", "prob", "cdf_estimation_method" ) tbl_out } #' Estimation of Failure Probabilities using the Nelson-Aalen Estimator #' #' @description #' `r lifecycle::badge("soft-deprecated")` #' #' `nelson_method()` is no longer under active development, switching to #' [estimate_cdf] is recommended. #' #' @details #' This non-parametric approach estimates the cumulative hazard rate in #' terms of (multiple) right censored data. By equating the definition of the #' hazard rate with the hazard rate according to Nelson-Aalen one can calculate #' the failure probabilities. #' #' @inheritParams johnson_method #' #' @return A tibble containing the following columns: #' #' * `id` : Identification for every unit. #' * `x` : Lifetime characteristic. #' * `status` : Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' * `rank` : Filled with `NA`. #' * `prob` : Estimated failure probabilities, `NA` if `status = 0`. #' * `cdf_estimation_method` : Specified method for the estimation of failure #' probabilities (always 'nelson'). #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' state <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' uic <- c("3435", "1203", "958X", "XX71", "abcd", "tz46", #' "fl29", "AX23","Uy12", "kl1a") #' #' # Example - Nelson-Aalen estimator applied to intact and failed units: #' tbl_nel <- nelson_method( #' x = obs, #' status = state, #' id = uic #' ) #' #' @md #' #' @export nelson_method <- function(x, status, id = NULL ) { deprecate_soft("2.0.0", "nelson_method()", "estimate_cdf()") if (!purrr::is_null(id)) { if (!((length(x) == length(status)) && (length(x) == length(id)))) { stop("'x', 'status' and 'id' must be of same length!", call. = FALSE) } } else { if (length(x) != length(status)) { stop("'x' and 'status' must be of same length!", call. = FALSE) } } data <- reliability_data(x = x, status = status, id = id) nelson_method_(data) } nelson_method_ <- function(data) { if (all(data$status == 1)) { warning( 'Use methods = "mr" since there is no censored data problem!', call. = FALSE ) } tbl_in <- data %>% # Remove additional classes tibble::as_tibble() tbl_calc <- tbl_in %>% dplyr::group_by(.data$x) %>% dplyr::mutate( failure = sum(.data$status == 1), survivor = sum(.data$status == 0) ) %>% dplyr::distinct(.data$x, .keep_all = TRUE) %>% dplyr::arrange(.data$x) %>% dplyr::ungroup() %>% dplyr::mutate( n_out = .data$failure + .data$survivor, n_in = nrow(data) - dplyr::lag(cumsum(.data$n_out), n = 1L, default = 0), lam_nel = ifelse(.data$status == 1, .data$failure / .data$n_in, 0), H_nel = cumsum(.data$lam_nel), prob = 1 - exp(-.data$H_nel) ) tbl_out <- tbl_in %>% dplyr::arrange(.data$x) %>% dplyr::mutate( rank = NA_real_, prob = ifelse( .data$status == 1, tbl_calc$prob[match(.data$x[order(.data$x)], tbl_calc$x)], NA_real_ ), cdf_estimation_method = "nelson" ) %>% dplyr::relocate( "id", "x", "status", "rank", "prob", "cdf_estimation_method" ) tbl_out }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/probability_estimators.R
#' R-Squared-Profile Function for Parametric Lifetime Distributions with Threshold #' #' @description #' This function evaluates the coefficient of determination with respect to a #' given threshold parameter of a parametric lifetime distribution. In terms of #' *Rank Regression* this function can be optimized ([optim][stats::optim]) to #' estimate the threshold parameter. #' #' @inheritParams rank_regression #' @param thres A numeric value for the threshold parameter. #' @param distribution Supposed parametric distribution of the random variable. #' #' @return #' Returns the coefficient of determination with respect to the threshold #' parameter `thres`. #' #' @encoding UTF-8 #' #' @examples #' # Data: #' data <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Probability estimation: #' prob_tbl <- estimate_cdf( #' data, #' methods = "johnson" #' ) #' #' # Determining the optimal coefficient of determination: #' ## Range of threshold parameter must be smaller than the first failure: #' threshold <- seq( #' 0, #' min( #' dplyr::pull( #' dplyr::filter( #' prob_tbl, #' status == 1, #' x == min(x) #' ), #' x #' ) - 0.1 #' ), #' length.out = 100 #' ) #' #' ## Coefficient of determination with respect to threshold values: #' profile_r2 <- r_squared_profiling( #' x = dplyr::filter( #' prob_tbl, #' status == 1 #' ), #' thres = threshold, #' distribution = "weibull3" #' ) #' #' ## Threshold value (among the candidates) that maximizes the coefficient of determination: #' threshold[which.max(profile_r2)] #' #' ## plot: #' plot( #' threshold, #' profile_r2, #' type = "l" #' ) #' abline( #' v = threshold[which.max(profile_r2)], #' h = max(profile_r2), #' col = "red" #' ) #' #' @md #' #' @export r_squared_profiling <- function(x, ...) { UseMethod("r_squared_profiling") } #' @rdname r_squared_profiling #' #' @export r_squared_profiling.wt_cdf_estimation <- function(x, thres, distribution = c( "weibull3", "lognormal3", "loglogistic3", "exponential2" ), direction = c( "x_on_y", "y_on_x" ), ... ) { r_squared_profiling.default( x = x$x, y = x$prob, thres = thres, distribution = distribution, direction = direction ) } #' R-Squared-Profile Function for Parametric Lifetime Distributions with Threshold #' #' @inherit r_squared_profiling description details return #' #' @inheritParams r_squared_profiling #' #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param y A numeric vector which consists of estimated failure probabilities #' regarding the lifetime data in x. #' #' @seealso [r_squared_profiling] #' #' @examples #' # Vectors: #' cycles <- alloy$cycles #' status <- alloy$status #' #' # Probability estimation: #' prob_tbl <- estimate_cdf( #' x = cycles, #' status = status, #' method = "johnson" #' ) #' #' # Determining the optimal coefficient of determination: #' ## Range of threshold parameter must be smaller than the first failure: #' threshold <- seq( #' 0, #' min(cycles[status == 1]) - 0.1, #' length.out = 100 #' ) #' #' ## Coefficient of determination with respect to threshold values: #' profile_r2 <- r_squared_profiling( #' x = prob_tbl$x[prob_tbl$status == 1], #' y = prob_tbl$prob[prob_tbl$status == 1], #' thres = threshold, #' distribution = "weibull3" #' ) #' #' ## Threshold value (among the candidates) that maximizes the #' ## coefficient of determination: #' threshold[which.max(profile_r2)] #' #' ## plot: #' plot( #' threshold, #' profile_r2, #' type = "l" #' ) #' abline( #' v = threshold[which.max(profile_r2)], #' h = max(profile_r2), #' col = "red" #' ) #' #' @md #' #' @export r_squared_profiling.default <- function(x, y, thres, distribution = c( "weibull3", "lognormal3", "loglogistic3", "exponential2" ), direction = c("x_on_y", "y_on_x"), ... ) { if (any(is.na(y))) { stop( "At least one of the failure probabilities ('y') is NA!", .call = FALSE ) } distribution <- match.arg(distribution) direction <- match.arg(direction) r_sq_prof_vectorized <- Vectorize( FUN = r_squared_profiling_, vectorize.args = "thres" ) r_sq_prof_vectorized( x = x, y = y, thres = thres, distribution = distribution, direction = direction ) } r_squared_profiling_ <- function(x, y, thres, distribution, direction ) { # Subtracting value of threshold, i.e. influence of threshold is eliminated: x_thres <- x - thres # Rank Regression: rr <- lm_( x = x_thres, y = y, distribution = distribution, direction = direction ) summary(rr)$r.squared }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/r_squared_function.R
#' Rank Regression for Parametric Lifetime Distributions #' #' @description #' This function fits a regression model to a linearized parametric lifetime #' distribution for complete and (multiple) right-censored data. The parameters #' are determined in the frequently used (log-)location-scale parameterization. #' #' For the Weibull, estimates are additionally transformed such that they are in #' line with the parameterization provided by the *stats* package #' (see [Weibull][stats::Weibull]). #' #' @details #' The confidence intervals of the parameters are computed on the basis of a #' heteroscedasticity-consistent (**HC**) covariance matrix. Here it should be #' said that there is no statistical foundation to determine the standard errors #' of the parameters using *Least Squares* in context of *Rank Regression*. #' For an accepted statistical method use [maximum likelihood][ml_estimation]. #' #' If `options = list(conf_method = "Mock")`, the argument `distribution` must be #' one of `"weibull"` and `"weibull3"`. The approximated confidence intervals #' for the Weibull parameters can then only be estimated on the following #' confidence levels (see 'References' *(Mock, 1995)*): #' #' * `conf_level = 0.90` #' * `conf_level = 0.95` #' * `conf_level = 0.99` #' #' @param x A `tibble` with class `wt_cdf_estimation` returned by [estimate_cdf]. #' @param distribution Supposed distribution of the random variable. #' @param conf_level Confidence level of the interval. #' @param direction Direction of the dependence in the regression model. #' @param control A list of control parameters (see [optim][stats::optim]). #' #' `control` is in use only if a three-parametric distribution was specified. #' If this is the case, `optim` (always with `method = "L-BFGS-B"` and #' `control$fnscale = -1`) is called to determine the threshold parameter #' (see [r_squared_profiling]). #' #' @param options A list of named options. See 'Options'. #' @template dots #' #' @template return-rank-regression #' @templateVar data A `tibble` with class `wt_cdf_estimation` returned by [estimate_cdf]. #' @return #' If more than one method was specified in [estimate_cdf], the resulting output #' is a list with class `wt_model_estimation_list`. In this case, each list element #' has classes `wt_rank_regression` and `wt_model_estimation`, and the items listed #' above, are included. #' #' @section Options: #' Argument `options` is a named list of options: #' #' | Name | Value | #' | :--------------- | :--------------------------------------- | #' | `conf_method` | `"HC"` (default) or `"Mock"` | #' #' @encoding UTF-8 #' #' @references #' #' * Mock, R., Methoden zur Datenhandhabung in Zuverlässigkeitsanalysen, #' vdf Hochschulverlag AG an der ETH Zürich, 1995 #' * Meeker, William Q; Escobar, Luis A., Statistical methods for reliability data, #' New York: Wiley series in probability and statistics, 1998 #' #' @examples #' # Reliability data preparation: #' ## Data for two-parametric model: #' data_2p <- reliability_data( #' shock, #' x = distance, #' status = status #' ) #' #' ## Data for three-parametric model: #' data_3p <- reliability_data( #' alloy, #' x = cycles, #' status = status #' ) #' #' # Probability estimation: #' prob_tbl_2p <- estimate_cdf( #' data_2p, #' methods = "johnson" #' ) #' #' prob_tbl_3p <- estimate_cdf( #' data_3p, #' methods = "johnson" #' ) #' #' prob_tbl_mult <- estimate_cdf( #' data_3p, #' methods = c("johnson", "kaplan") #' ) #' #' # Example 1 - Fitting a two-parametric weibull distribution: #' rr_2p <- rank_regression( #' x = prob_tbl_2p, #' distribution = "weibull" #' ) #' #' # Example 2 - Fitting a three-parametric lognormal distribution: #' rr_3p <- rank_regression( #' x = prob_tbl_3p, #' distribution = "lognormal3", #' conf_level = 0.99 #' ) #' #' # Example 3 - Fitting a three-parametric lognormal distribution using #' # direction and control arguments: #' rr_3p_control <- rank_regression( #' x = prob_tbl_3p, #' distribution = "lognormal3", #' conf_level = 0.99, #' direction = "y_on_x", #' control = list(trace = TRUE, REPORT = 1) #' ) #' #' # Example 4 - Fitting a three-parametric loglogistic distribution if multiple #' # methods in estimate_cdf were specified: #' rr_lists <- rank_regression( #' x = prob_tbl_mult, #' distribution = "loglogistic3", #' conf_level = 0.90 #' ) #' #' @md #' #' @export rank_regression <- function(x, ...) { UseMethod("rank_regression") } #' @rdname rank_regression #' #' @export rank_regression.wt_cdf_estimation <- function( x, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), conf_level = 0.95, direction = c("x_on_y", "y_on_x"), control = list(), options = list(), ... ) { distribution <- match.arg(distribution) direction <- match.arg(direction) if (length(unique(x$cdf_estimation_method)) == 1) { rank_regression_( cdf_estimation = x, distribution = distribution, conf_level = conf_level, direction = direction, control = control, options = options ) } else { # Apply rank_regression to each cdf estimation method separately x_split <- split(x, x$cdf_estimation_method) model_estimation_list <- purrr::map(x_split, function(cdf_estimation) { rank_regression_( cdf_estimation = cdf_estimation, distribution = distribution, conf_level = conf_level, direction = direction, control = control, options = options ) }) class(model_estimation_list) <- c( "wt_model", "wt_model_estimation_list", class(model_estimation_list) ) model_estimation_list } } #' Rank Regression for Parametric Lifetime Distributions #' #' @inherit rank_regression description details references #' @inheritSection rank_regression Options #' #' @inheritParams rank_regression #' @param x A numeric vector which consists of lifetime data. Lifetime data #' could be every characteristic influencing the reliability of a product, #' e.g. operating time (days/months in service), mileage (km, miles), load #' cycles. #' @param y A numeric vector which consists of estimated failure probabilities #' regarding the lifetime data in `x`. #' @param status A vector of binary data (0 or 1) indicating whether a unit is #' a right censored observation (= 0) or a failure (= 1). #' #' @template return-rank-regression #' @templateVar data A `tibble` with columns `x`, `status` and `prob`. #' #' @seealso [rank_regression] #' #' @examples #' # Vectors: #' obs <- seq(10000, 100000, 10000) #' status_1 <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) #' #' cycles <- alloy$cycles #' status_2 <- alloy$status #' #' # Example 1 - Fitting a two-parametric weibull distribution: #' tbl_john <- estimate_cdf( #' x = obs, #' status = status_1, #' method = "johnson" #' ) #' #' rr <- rank_regression( #' x = tbl_john$x, #' y = tbl_john$prob, #' status = tbl_john$status, #' distribution = "weibull", #' conf_level = 0.90 #' ) #' #' # Example 2 - Fitting a three-parametric lognormal distribution: #' tbl_kaplan <- estimate_cdf( #' x = cycles, #' status = status_2, #' method = "kaplan" #' ) #' #' rr_2 <- rank_regression( #' x = tbl_kaplan$x, #' y = tbl_kaplan$prob, #' status = tbl_kaplan$status, #' distribution = "lognormal3" #' ) #' #' @md #' #' @export rank_regression.default <- function(x, y, status, distribution = c( "weibull", "lognormal", "loglogistic", "sev", "normal", "logistic", "weibull3", "lognormal3", "loglogistic3", "exponential", "exponential2" ), conf_level = 0.95, direction = c("x_on_y", "y_on_x"), control = list(), options = list(), ... ) { distribution <- match.arg(distribution) direction <- match.arg(direction) cdf_estimation <- tibble::tibble(x = x, status = status, prob = y) rank_regression_( cdf_estimation = cdf_estimation, distribution = distribution, conf_level = conf_level, direction = direction, control = control, options = options ) } # Function that performs the parameter estimation: rank_regression_ <- function(cdf_estimation, distribution, conf_level, direction, control, options ) { # In terms of RR only failed items can be used: cdf_failed <- cdf_estimation %>% dplyr::filter(.data$status == 1) x_f <- cdf_failed$x y_f <- cdf_failed$prob # Pre-Step: Threshold models must be profiled w.r.t threshold: if (has_thres(distribution)) { ## Force maximization: control$fnscale <- -1 ## Optimization using `r_squared_profiling()`: opt_thres <- stats::optim( par = 0, fn = r_squared_profiling, method = "L-BFGS-B", upper = (1 - (1 / 1e+5)) * min(x_f), lower = 0, control = control, x = x_f, y = y_f, distribution = distribution ) opt_thres <- opt_thres$par ## Preparation for lm: x_thres <- x_f - opt_thres subs <- x_thres > 0 x_f <- x_thres[subs] y_f <- y_f[subs] } # Step 1: Model estimation using RR: rr <- lm_( x = x_f, y = y_f, distribution = distribution, direction = direction ) ## Parameters: dist_params <- stats::coef(rr) if (std_parametric(distribution) == "exponential") { names(dist_params) <- "sigma" } else { names(dist_params) <- c("mu", "sigma") } ### Threshold parameter: if (exists("opt_thres", inherits = FALSE)) { dist_params <- c(dist_params, opt_thres) names(dist_params)[length(dist_params)] <- "gamma" } # Step 2: Confidence intervals computation based on 'options': ## Value of argument 'options': conf_option <- options$conf_method %||% "HC" ## Confidence intervals with HC standard errors: if (conf_option == "HC") { ### Estimating HC covariance matrix: dist_varcov <- sandwich::vcovHC(x = rr, type = "HC1") output <- conf_HC( dist_params = dist_params, dist_varcov = dist_varcov, distribution = distribution, conf_level = conf_level, n = length(x_f), direction = direction ) } else { if (distribution %in% c("weibull", "weibull3")) { ## Confidence intervals according to Mock for 'weibull' and 'weibull3': output <- conf_mock( dist_params = dist_params, conf_level = conf_level, n = length(x_f), direction = direction ) } else { stop( "For option conf_method = 'Mock', the distribution argument needs to be", " 'weibull' or 'weibull3' but " , sQuote(distribution), " was used!", call. = FALSE ) } } # Step 3: Form output: r_sq <- summary(rr)$r.squared rr_output <- c( output, r_squared = r_sq ) rr_output$data = cdf_estimation rr_output$distribution = distribution rr_output$direction = direction class(rr_output) <- c( "wt_model", "wt_rank_regression", "wt_model_estimation", class(rr_output) ) rr_output } #' @export print.wt_rank_regression <- function(x, digits = max(3L, getOption("digits") - 3L), ... ) { cat("Rank Regression\n") NextMethod("print") }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/rank_regression.R
# Helper function that performs lm(): lm_ <- function(x, y, distribution, direction = c("x_on_y", "y_on_x") ) { direction <- match.arg(direction) distribution <- std_parametric(distribution) # Prepare x and y for `lm()`: y <- q_std(y, distribution) if (distribution %in% c("weibull", "lognormal", "loglogistic")) { x <- log(x) } # Create formula to be more flexible w.r.t 'distribution' and 'direction': ## Replace everything between the two underscores: fm_chr <- sub("_[^>]+_", " ~ ", direction) ## If distribution is 'exponential', the intercept is 0: if (distribution == "exponential") { fm_chr <- paste(fm_chr, "- 1") } ## Define formula: fm <- stats::formula(fm_chr) ## Apply `lm()` to defined formula: stats::lm(fm) } # Approximated confidence intervals for parameters according to Mock: conf_mock <- function(dist_params, # loc-scale-parameters conf_level, n, # sample size direction ) { # Check for conf_level: if (!(conf_level %in% c(0.9, 0.95, 0.99))) { stop( "'conf_level' must be 0.90, 0.95 or 0.99", call. = FALSE ) } # Lookup: conf <- as.character(conf_level) mock_val <- c("0.9" = 1.4, "0.95" = 2, "0.99" = 3.4)[[conf]] # Consider direction: if (direction == "y_on_x") { ## Back-transformed parameters: dist_params[1:2] <- c( -dist_params[[1]] / dist_params[[2]], 1 / dist_params[[2]] ) } # Alternative parameters for Weibull: estimates <- dist_params estimates[1:2] <- c(exp(estimates[[1]]), 1 / estimates[[2]]) names(estimates)[1:2] <- c("eta", "beta") # Confidence intervals: p_conf <- c((1 + conf_level), (1 - conf_level)) / 2 q_chi <- stats::qchisq( p = p_conf, df = 2 * n + 2 ) conf_beta <- estimates[["beta"]] * c( 1 / (1 + sqrt(mock_val / n)), (1 + sqrt(mock_val / n)) ) conf_eta <- estimates[["eta"]] * (2 * n / q_chi) ^ (1 / estimates[["beta"]]) # Form confidence interval matrix: conf_int <- matrix(c(conf_eta, conf_beta), byrow = TRUE, ncol = 2) colnames(conf_int) <- paste(rev(p_conf) * 100, "%") if (length(estimates) > 2L) { conf_gamma <- estimates[["gamma"]] * (2 * n / q_chi) ^ (1 / estimates[["beta"]]) conf_int <- rbind(conf_int, conf_gamma) } rownames(conf_int) <- names(estimates) # Alternative confidence interval matrix: conf_int_loc_sc <- conf_int conf_int_loc_sc[1, ] <- log(conf_int_loc_sc[1, ]) conf_int_loc_sc[2, ] <- rev(1 / conf_int_loc_sc[2, ]) rownames(conf_int_loc_sc) <- names(dist_params) # Return a list: list( coefficients = dist_params, confint = conf_int_loc_sc, shape_scale_coefficients = estimates, shape_scale_confint = conf_int ) } # Confidence intervals for parameters using a HC standard errors: conf_HC <- function(dist_params, # loc-scale-parameters (or scale-parameter). dist_varcov, # loc-scale-var-cov (or scale-variance). distribution, # Setting the parameter name for exponential. conf_level, n, # sample size direction ) { n_par <- nrow(dist_varcov) colnames(dist_varcov) <- rownames(dist_varcov) <- names(dist_params)[1:n_par] # Standard errors: dist_se <- sqrt(diag(dist_varcov)) # Studentized confidence intervals: p_conf <- c((1 - conf_level), (1 + conf_level)) / 2 q_t <- stats::qt( p = p_conf, df = n - 2 ) # Compute confidence intervals using `sapply()` (matrix with named columns): conf_int <- sapply( names(dist_se), function(x) dist_params[[x]] + q_t * dist_se[[x]] ) # Consider direction, i.e. back-transformation for parameters and intervals: if (direction == "y_on_x") { ## For scale sigma: dist_params[["sigma"]] <- 1 / dist_params[["sigma"]] conf_int[, "sigma"] <- rev(1 / conf_int[, "sigma"]) ## For location mu, if exists: if (n_par == 2L) { dist_params[["mu"]] <- -dist_params[["mu"]] * dist_params[["sigma"]] conf_int[, "mu"] <- -conf_int[, "mu"] * conf_int[, "sigma"] } } # Prepare matrix with confidence intervals for output: ## Force sorting of interval (prevent case that conf_mu[1] > conf_mu[2]) conf_int <- t(apply(conf_int, 2, sort)) ## Set column names: colnames(conf_int) <- paste(p_conf * 100, "%") ## Exponential distribution: if (std_parametric(distribution) == "exponential") { names_exp <- "theta" ### Set name: names(dist_params)[n_par] <- rownames(conf_int) <- names_exp dimnames(dist_varcov) <- rep(list(names_exp), 2) } ## Three-parametric case: if (length(dist_params) > n_par) { conf_int <- rbind(conf_int, c(NA, NA)) rownames(conf_int)[n_par + 1] <- names(dist_params[n_par + 1]) } ## Alternative parameters and confidence intervals for Weibull: l_wb <- list() ## Weibull distribution; providing shape-scale coefficients and confint: if (distribution %in% c("weibull", "weibull3")) { estimates <- to_shape_scale_params(dist_params) confint <- to_shape_scale_confint(conf_int) l_wb <- list( shape_scale_coefficients = estimates, shape_scale_confint = confint ) } # Return a list: c( list( coefficients = dist_params, confint = conf_int ), l_wb, # Empty, if not Weibull! list(varcov = dist_varcov) ) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/rank_regression_helpers.R
#' Reliability Data #' #' @description #' Create consistent reliability data based on an existing `data.frame` #' (preferred) or on multiple equal length vectors. #' #' @param data Either `NULL` or a `data.frame`. If data is `NULL`, #' `x`, `status` and `id` must be vectors containing #' the data. Otherwise `x`, `status` and `id` can be either column #' names or column positions. #' @param x Lifetime data, that means any characteristic influencing the reliability #' of a product, e.g. operating time (days/months in service), mileage (km, miles), #' load cycles. #' @param status Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' @param id Identification of every unit. #' @param .keep_all If `TRUE` keep remaining variables in `data`. #' #' @return A tibble with class `wt_reliability_data` containing the following #' columns (if `.keep_all = FALSE`): #' #' * `x` : Lifetime characteristic. #' * `status` : Binary data (0 or 1) indicating whether a unit is a right #' censored observation (= 0) or a failure (= 1). #' * `id` : Identification for every unit. #' #' If `.keep_all = TRUE`, the remaining columns of `data` are also preserved. #' #' If `!is.null(data)` the attribute `characteristic` holds the name of the #' characteristic described by `x`. Otherwise it is set to `"x"`. #' #' @examples #' # Example 1 - Based on an existing data.frame/tibble and column names: #' data <- reliability_data( #' data = shock, #' x = distance, #' status = status #' ) #' #' # Example 2 - Based on an existing data.frame/tibble and column positions: #' data_2 <- reliability_data( #' data = shock, #' x = 1, #' status = 3 #' ) #' #' # Example 3 - Keep all variables of the tibble/data.frame entered to argument data: #' data_3 <- reliability_data( #' data = shock, #' x = distance, #' status = status, #' .keep_all = TRUE #' ) #' #' # Example 4 - Based on vectors: #' cycles <- alloy$cycles #' state <- alloy$status #' id <- "XXXXXX" #' #' data_4 <- reliability_data( #' x = cycles, #' status = state, #' id = id #' ) #' #' @md #' #' @export reliability_data <- function(data = NULL, x, status, id = NULL, .keep_all = FALSE ) { if (purrr::is_null(data)) { # Vector based approach ---------------------------------------------------- if (!is_characteristic(x)) { stop("'x' must be numeric!", call. = FALSE) } if (!is_status(status)) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } if (purrr::is_null(id)) { id <- paste0("ID", seq_along(x)) } tbl <- tibble::tibble(x = x, status = status, id = id) characteristic <- "x" } else { # Data based approach ----------------------------------------------------- if (!is_characteristic(dplyr::select(data, x = {{x}})[[1]])) { stop("'x' must be numeric!", call. = FALSE) } if (!is_status(dplyr::select(data, status = {{status}})[[1]])) { stop("'status' must be numeric with elements 0 or 1!", call. = FALSE) } x_def <- dplyr::enexpr(x) characteristic <- if (is.numeric(x_def)) { # Column index names(data)[x_def] } else { # Column name as.character(x_def) } data <- tibble::as_tibble(data) if (.keep_all) { tbl <- dplyr::rename(data, x = {{x}}, status = {{status}}, id = {{id}}) } else { tbl <- dplyr::select(data, x = {{x}}, status = {{status}}, id = {{id}}) } if (!"id" %in% names(tbl)) { tbl$id <- paste0("ID", seq_len(nrow(data))) } tbl <- dplyr::relocate(tbl, x, status, id) } class(tbl) <- c("wt_reliability_data", class(tbl)) # Mark column x as characteristic attr(tbl, "characteristic") <- characteristic tbl } #' @export print.wt_reliability_data <- function(x, ...) { if (attr(x, "characteristic") == "x") { cat("Reliability Data:\n") } else { cat( "Reliability Data with characteristic x: '", attr(x, "characteristic"), "':\n", sep = "" ) } NextMethod() } is_characteristic <- function(x) { is.numeric(x) } is_status <- function(x) { is.numeric(x) && all(x %in% c(0, 1)) }
/scratch/gouwar.j/cran-all/cranData/weibulltools/R/reliability_data.R