I have a dataset with many columns that, by each row value combination, determine a set of rules for a new value in another column. The different combinations are diverse, and not all columns are included for each rule. Also, some columns have organism names that tend to be quite long. Due to this, the current method I am using (case_when
) becomes quite messy, and reviewing these rules becomes quite tedious.
I am wondering if there is a better way of doing this that is cleaner and easier to review? The dataset I run this on has over 70.000 observations, so below is a dummy dataset that can be used.
col1 col2 col3 col4 col5 col6
1 A 43 string1 AA verylongnamehere
2 B 22 string2 BB anotherlongname
3 C 15 string3 CC yetanotherlongname
4 D 100 string4 DD hereisanotherlongname
5 E 60 string5 EE thisisthelastlongname
test <- data.frame(
col1 = c(1,2,3,4,5),
col2 = c("A","B","C","D","E"),
col3 = c(43,22,15,100,60),
col4 = c("string1","string2","string3","string4","string5"),
col5 = c("AA","BB","CC","DD","EE"),
col6 = c("verylongnamehere", "anotherlongname","yetanotherlongname","hereisanotherlongname","thisisthelastlongname")
)
The following code is an example of the rules and code I use:
library(dplyr)
test2 <- test %>%
mutate(new_col = case_when(
col1 == 1 & col2 == "A" & col6 == "verylongnamehere" ~ "result1",
col3 >= 60 & col5 == "DD" ~ "result2",
col1 %in% c(2,3,4) &
col2 %in% c("B","D") &
col5 %in% c("BB","CC","DD") &
col6 %in% c("anotherlongname","yetanotherlongname") ~ "result3",
TRUE ~ "result4"
))