user18894435
user18894435

Reputation: 521

Convert values outside a range to the range's bounds

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

Upvotes: 2

Views: 160

Answers (1)

akrun
akrun

Reputation: 886948

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

Upvotes: 2

Related Questions