Maximum number of continuous "runs" of values meeting a particular condition
Source:R/maxRuns.r
maxRuns.Rd
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
.
Arguments
- x
Vector of numeric, character, or other values.
- fx
A function that returns
TRUE
,FALSE
, or (optionally)NA
. The function must usex
as its first argument. For example,function(x) x == 0
is allowable, butfunction(y) y == 0
is not. Values that count asTRUE
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 areNA
after being evaluated byfx
.
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)
#> [1] 3
fx <- function(x) x > 0
maxRuns(x, fx)
#> [1] 2
fx <- function(x) x > 0 & x < 5
maxRuns(x, fx)
#> [1] 2
x <- c(1, 4, 0, 0, 0, 2, 0, 10)
fx <- function(x, th) x == th
maxRuns(x, fx, args=list(th=0))
#> [1] 3
# "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))
#> [1] 3
# 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))
#> [1] 5