Home > Enterprise >  Rounding numbers to the nearest values (with different intervals) in R
Rounding numbers to the nearest values (with different intervals) in R

Time:11-22

I want to round (or replace) numbers in a

a <- c(0.505, 1.555, 2.667, 53.850, 411.793)

to the nearest values in b:

b <- c(0, 5, 10, 50, 100, 200, 500)

The output will be this:

a_rnd <- c(0, 0, 5, 50, 500)

The logic is simple but I couldn't find any solution, because all the approaches I found require values in b have an equal interval!

How can I achieve this?

CodePudding user response:

You can use sapply to loop over all values of a and use these indexes to extract the proper b values

b[sapply(a, function(x) which.min(abs(x - b)))]
#> [1]   0   0   5  50 500

CodePudding user response:

This is a relatively simple approach:

b[apply(abs(outer(a, b, "-")), 1, which.min)]
  • Related