Juan_814
Juan_814

Reputation: 124

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

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?

Upvotes: 1

Views: 246

Answers (2)

user2554330
user2554330

Reputation: 44977

This is a relatively simple approach:

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

Upvotes: 2

mnist
mnist

Reputation: 6954

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

Upvotes: 3

Related Questions