Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active May 19, 2021 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brshallo/f3f1ba8e236e0d6c6339face7b9a3dab to your computer and use it in GitHub Desktop.
Save brshallo/f3f1ba8e236e0d6c6339face7b9a3dab to your computer and use it in GitHub Desktop.
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment