library(tidyverse)
data <- tibble(
a = c(0, 0, 1),
b = c(0, 1, 0),
c = c(1, 1, 1)
)
data_sums <- data %>%
rowwise() %>%
mutate(total = sum(c_across(a:c)))
concat_drop_0s <- function(...){
str_subset(..., "[^0]") %>%
str_c(collapse = " + ")
}
data_sums %>%
select(a, b, c) %>%
purrr::imodify(~ifelse(.x, .y, 0)) %>%
mutate(mix = concat_drop_0s(c_across(a:c))) %>%
bind_cols(select(data_sums, -c(a, b, c)), .) %>%
ungroup()
#> # A tibble: 3 x 5
#> total a b c mix
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 1 0 0 c c
#> 2 2 0 b c b + c
#> 3 2 a 0 c a + c
Created on 2021-05-19 by the reprex package (v2.0.0)