Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading