I have a data frame df with a column x and I would like to create another column y that is determined by some cut points which I would like to provide to a function as an input.
The function should take an indeterminated number of cut points such as in the example below 0, 5, 10, 15. The function should take another input with the corresponding values for the y variable. In the example 3, 6, 9, 12.
library(tidyverse)
df <- tibble(x = 0:20)
mutate(df, y = case_when(x >= 0 & x < 5 ~ 3,
x >= 5 & x < 10 ~ 6,
x >= 10 & x < 15 ~ 9,
x >= 15 ~ 12))
my_cut_points <- c(0, 5, 10, 15)
my_corr_values <- c(3, 6, 9, 12)
my_func <- function(df, cut_points = my_cut_points, corr_values = my_corr_values) {
...
}
The solution needs to take input vectors of various lengths. However the pattern is always the same. The lower cut point sould be included in the interval and the upper cut point should not be included. It does not need to use case_when. It could also use cut or whatever provides the correct result.