Home > Software design >  Convert values outside a range to the range's bounds
Convert values outside a range to the range's bounds

Time:06-21

If I have a series of values

set.seed(123)
x <- rnorm(100)

and a given range (a, b), e.g.

a <- -1; b <- 2

How could I move those values less than a to a and those greater than b to b?

The following basic method works but I'm searching a function or a one-liner command.

x[x < a] <- a
x[x > b] <- b

CodePudding user response:

If we need a single line, use pmin/pmax

out <- pmin(pmax(x, a), b)

-checking

x[x < a] <- a
x[x > b] <- b
identical(out, x)
[1] TRUE
  • Related