I often find myself having to apply the following condition: I have a table with multiple binary columns rated yes/no or 0/1. I have to create a new intermediate column in the calculations with the following rule: if all columns are "no", then the new column is "no", if at least one column has "yes", then the summary column must express "yes". I usually do this with case_when, and it works well (see example).
library(tidyverse)
#create a table for reproducible example
set.seed(001)
carac1 <- round(runif(100),0)
carac2 <- round(runif(100),0)
carac3 <- round(runif(100),0)
data <- data.frame(carac1,carac2,carac3)
#apply case_when with complex condition
data <- data %>%
mutate(carac_all = case_when(
carac1 == 0 & carac2 == 0 & carac3 == 0 ~ "Always no",
carac1 == 1 | carac2 == 1 | carac3 == 1 ~ "yes at least one time",
TRUE ~ NA_character_))
This give me exactly what i want :
carac1 carac2 carac3 carac_all
1 0 1 0 yes at least one time
2 0 0 0 Always no
3 1 0 1 yes at least one time
4 1 1 0 yes at least one time
(This example is with a number 0/1 but sometimes it's with a character yes/no or other categorial variable, such as color ... so the trick to use >0 is not simple to implement in these cases.)
The problem is that this code forces me to enter the name of each column in the code. On my last file, I have 120 successive columns to analyse ... Is there any way to use case_when with this kind of conditions on a range of columns? I tried carac1:carac3 == 0, but it doesn't work, and anyway I don't see how to express the "at least one column says yes".
Thanks for your help.
TLDR: I want to simplify the code I'm currently using so that I don't have to enter the name of each variable in the code, but a range of variables.