I know there is a better way or some type of loop to do this, but what would be the best way to do the mutate/case_when step below instead of doing so many mutate steps. Essentially, I'm trying to add 168 columns to the "new" dataset, one for each "type", where "group1" will always be "A", and then again where "group2" will always be "C". There are 84 unique types.
library(tidyverse)
set.seed(42)
n <- 84
datA <- data.frame(id=1:n,
type=factor(paste("type", 1:n)),
group1=sample(rep(LETTERS[1:2], n/2)),
group2=sample(rep(LETTERS[3:4], n/2)))
datB <- data.frame(id=1:n,
type=factor(paste("type", 1:n)),
group1=sample(rep(LETTERS[1:2], n/2)),
group2=sample(rep(LETTERS[3:4], n/2)))
dat <- rbind(datA, datB)
new <- dat %>%
mutate(type1Group1 = case_when(
(type == "type 1" & group1 == "A") ~ TRUE,
)) %>%
mutate(type1Group2 = case_when(
(type == "type 1" & group2 == "C") ~ TRUE,
))%>%
mutate(type2Group1 = case_when(
(type == "type 2" & group1 == "A") ~ TRUE,
))%>%
mutate(type2Group2 = case_when(
(type == "type 2" & group2 == "C") ~ TRUE,
))