set_limits: Set values outside range to upper/lower limits

View source: R/math_funcs.R

set_limitsR Documentation

Set values outside range to upper/lower limits

Description

Given a numeric vector and lower and upper limits of allowed values, set the values outside the accepted range to the nearest limit.

Usage

set_limits(v, lower = -Inf, upper = Inf, na.rm = TRUE)

Arguments

v

Numeric vector

lower

Lower limit, single numeric value

upper

Upper limit, single numeric value

na.rm

How to treat NA values

Details

Other methods to get the same result:

  1. ifelse(v>upper,upper,ifelse(v<lower,lower,v))

  2. v[v<upper] <- upper; v[v>lower] <- lower

(1) is slowest, (2) is sometimes faster than set_limits (note: this has not been tested extensively)

Value

Numeric vector where values beyond the accepted range have been converted to the lower/upper limits

Examples

v <- 1:10
l <- 3
v <- set_limits(v,l)

v <- rnorm(1e5)
l <- -2
u <- 2

ptm <- Sys.time()
v <- set_limits(v,l,u)
print(Sys.time()-ptm)

ptm <- Sys.time()
v[v<l] <- l
v[v>u] <- u
print(Sys.time()-ptm)


BIO-RSG/oceancolouR documentation built on April 30, 2024, 7:54 a.m.