maxRuns: Maximum number of continuous "runs" of values meeting a...

maxRunsR Documentation

Maximum number of continuous "runs" of values meeting a particular condition

Description

Consider an ordered set of values, say 0, 4, 0, 0, 0, 2, 0, 10. We can ask, "What is the number of times in which zeros appear successively?" This function can answer this question and similar ones. What is considered a "run" is defined by a user-supplied function that must have a TRUE/FALSE output. For example, a "run" could be any succession of values less than two, in which case the criterion function would be function(x) < 2, or any succession of values not equal to 0, in which case the function would be function(x) x != 0.

Usage

maxRuns(x, fx, args = NULL, failIfAllNA = FALSE)

Arguments

x

Vector of numeric, character, or other values.

fx

A function that returns TRUE, FALSE, or (optionally) NA. The function must use x as its first argument. For example, function(x) x == 0 is allowable, but function(y) y == 0 is not. Values that count as TRUE will be counted toward a run.

args

A list object with additional arguments to supply to the function fx.

failIfAllNA

If TRUE, fail if all values are NA after being evaluated by fx.

Value

Lengths of successive runs of elements that meet the criterion. A single value of 0 indicates no conditions meet the criterion.

Examples


x <- c(1, 4, 0, 0, 0, 2, 0, 10)
fx <- function(x) x == 0
maxRuns(x, fx)

fx <- function(x) x > 0
maxRuns(x, fx)
 
fx <- function(x) x > 0 & x < 5
maxRuns(x, fx)

x <- c(1, 4, 0, 0, 0, 2, 0, 10)
fx <- function(x, th) x == th
maxRuns(x, fx, args=list(th=0))

# "count" NA as an observation 
x <- c(1, 4, 0, 0, 0, NA, 0, 10)
fx <- function(x, th) ifelse(is.na(x), FALSE, x == th)
maxRuns(x, fx, args=list(th=0))
 
# include NAs as part of a run
x <- c(1, 4, 0, 0, 0, NA, 0, 10)
fx <- function(x, th) ifelse(is.na(x), TRUE, x == th)
maxRuns(x, fx, args=list(th=0))
 

adamlilith/omnibus documentation built on April 12, 2024, 8:46 p.m.