I found somewhat similar examples here and here, but I didn't follow the examples for the problem I am trying to solve.
What I would like to do is to use mutate and case_when to create a new column. The new column would create a category classification (e.g., "category_1") depending on the values from a different column. Since the number of values may change I want to make the case_when dynamic.
The problem is when this loop operates, it operates fine on each iteration, but when the loop advances it overwrites the previous values. So I am wondering how to use a case_when in a loop that would prevent the last loop value being evaluated while overwriting the previous iterations.
Here is a reproducible example:
library(tidyverse)
# Use built-in data frame for reproducible example
my_df <- mtcars
# Create sequence to reference beginning and end ranges within mpg values
mpg_vals <- sort(mtcars$mpg)
beg_seq <- seq(1, 31, 4)
end_seq <- seq(4, 32, 4)
# Create loop to fill in mpg category
for(i in 1:8){
my_df <- my_df %>%
mutate(mpg_class = case_when(
mpg %in% mpg_vals[beg_seq[i]:end_seq[i]] ~ paste0("category", i)
)
)
# Observe loop values
print(mpg_vals[beg_seq[i]:end_seq[i]])
print(paste0("category_", i))
}