I'm having trouble finding a solution for a complex variable assignment need. I need to create new variables based on the values in existing variables, but I need to do the same new variable creation many times using a different set of existing variables each time. So for example, I have the following data frame:
dat=data.frame(
kiwi_3=c(1,0,1),
kiwi_5=c(0,0,1),
kiwi_8=c(1,1,0),
apple_3=c(0,0,0),
apple_5=c(1,0,1),
apple_8=c(1,1,0))
I can use the following line of code to create a new variable based on values in existing variables:
dat<-dat %>%
mutate(fruit_3=case_when(kiwi_3==1 & apple_3==1~1,
kiwi_3==1 & apple_3==0~2))
However, what I need to do is to create variables for each number suffix (in this example, fruit_3, fruit_5, fruit_8) based on the variables with the same (non-sequential) number suffix, using the same logic. The actual logic is more complicated than in this example too so I would guess that using case_when will be necessary. I imagine there's a solution using dplyr mutate and across, possibly with indexed vectors with the variable names in them, but I haven't hit upon a solution that works yet.
Thanks for any suggestions!