I do like the case_when method, but if you didn't want to type it all out, you could create a function to accomplish your goal.
The below would need to be modified if you wanted to treat for the final else statement.
# load tidyverse
library(tidyverse)
# function ----
my_match <- function(match_tbl, n) {
match_df <- match_tbl %>%
rowid_to_column("key")
new_key <- nrow(match_df) + 1
match_df %>%
full_join(
tibble(
key = new_key,
input = n
),
by = c("key", "input")
) %>%
arrange(input) %>%
fill(output, .direction = "updown") %>%
filter(key == new_key) %>%
pull(output)
}
# break table ----
my_breaks <- tibble(
input = c(0.5, 0.8, 0.9, 0.97, 1),
output = c(0, 1, 2, 3, 4)
)
# test ----
tibble(
new_inputs = c(
(c(0.5, 0.8, 0.9, 0.97, 1) - .01),
(c(0.5, 0.8, 0.9, 0.97, 1) + .01)
)
) %>%
rowwise() %>%
mutate(matched_n = my_match(my_breaks,new_inputs)) %>%
ungroup()
#> # A tibble: 10 x 2
#> new_inputs matched_n
#> <dbl> <dbl>
#> 1 0.49 0
#> 2 0.79 1
#> 3 0.89 2
#> 4 0.96 3
#> 5 0.99 4
#> 6 0.51 1
#> 7 0.81 2
#> 8 0.91 3
#> 9 0.98 4
#> 10 1.01 4
Created on 2020-08-13 by the reprex package (v0.3.0)