How about this?
library(dplyr)
library(tidyr)
sample_df <- data.frame(
id = c(1, 2, 3),
cd_25 = c(0, 0, 1),
ivig = c(1, 0, 0),
b_cell = c(1, 1, 0)
)
sample_df %>%
gather(-id, key = induction_agent, value = presence) %>%
filter(presence == 1) %>%
group_by(id) %>%
summarise(induction_agent = paste(induction_agent, collapse = ", ")) %>%
right_join(sample_df)
#> Joining, by = "id"
#> # A tibble: 3 x 5
#> id induction_agent cd_25 ivig b_cell
#> <dbl> <chr> <dbl> <dbl> <dbl>
#> 1 1 ivig, b_cell 0 1 1
#> 2 2 b_cell 0 0 1
#> 3 3 cd_25 1 0 0
# If you prefer the "multiple" recode
sample_df %>%
gather(-id, key = induction_agent, value = presence) %>%
filter(presence == 1) %>%
add_count(id) %>%
mutate(induction_agent = if_else(n == 2, "multiple", induction_agent)) %>%
distinct(id, induction_agent) %>%
right_join(sample_df)
#> Joining, by = "id"
#> id induction_agent cd_25 ivig b_cell
#> 1 3 cd_25 1 0 0
#> 2 1 multiple 0 1 1
#> 3 2 b_cell 0 0 1
Created on 2021-02-21 by the reprex package (v1.0.0)