Reputation: 813
Wondering how x can round down to the nearest below value based on a separate numeric series (y). This is what I had in mind.
Let's say x is in 5s
> y
[1] 5 10 15 20 25 30 35 40 45
And y from a different object is equal to
> x
[1] 39
I'd like to see it round down to the nearest lower specified value from y
> x
[1] 35
Upvotes: 1
Views: 38
Reputation: 4169
You can use %/% and multiply it by y (if you set y to be your multiple, e.g. if 5's):
y <- 5
x <- 39
(x %/% y) * y
If you must use a vector of length > 1 for y then you could use a few different functions like max()
or tail(..., 1)
to get the largest or last value in y:
y <- seq(0, 50, 5)
tail(y[x > y], 1)
max(y[x > y])
Note that x > y
is creating a logical vector which is being used for a linear search, returning a vector of the values of y less than x and passing that to the function.
Upvotes: 4
Reputation: 388972
You could use findInterval
/cut
y <- seq(5, 45, 5)
x <- 39
y[findInterval(x, y)]
#[1] 35
With cut
:
y[cut(x, y, labels = FALSE)]
Upvotes: 2