R/calc_streak.R

Defines functions calc_streak

Documented in calc_streak

#' Calculate hitting streaks
#' 
#' @param x A data frame or character vector of hits (\code{"H"}) and misses (\code{"M"}).
#' @return A data frame with one column, \code{length}, containing the length of each hit streak.
#' @examples
#' data(kobe_basket)
#' calc_streak(kobe_basket$shot)
#' 
#' @export

calc_streak = function(x)
{
    if (!is.atomic(x))
        x = x[,1]

    if (any(!x %in% c("H","M")))
        stop('Input should only contain hits ("H") and misses ("M")')
    
    y = rep(0,length(x))
    y[x == "H"] = 1
    y = c(0, y, 0)
    wz = which(y == 0)
    streak = diff(wz) - 1
    
    return(data.frame(length = streak))
}

Try the statsr package in your browser

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

statsr documentation built on Jan. 23, 2021, 1:05 a.m.