title: dplyr case_when with dynamic number of cases
body: <p>Wanting to use dplyr and <code>case_when</code> to collapse a series of indicator columns into a single column. The challenge is I want to be able to collapse over an unspecified/dynamic number of columns.</p>
  
  <p>Consider the following dataset, <code>gear</code> has been split into a series of indicator columns.</p>
  
  <pre class="lang-r prettyprint-override"><code>library(dplyr)
  data(mtcars)
  mtcars = mtcars %&gt;%
    mutate(g2 = ifelse(gear == 2, 1, 0),
           g3 = ifelse(gear == 3, 1, 0),
           g4 = ifelse(gear == 4, 1, 0)) %&gt;%
    select(g2, g3, g4)
  </code></pre>
  
  <p>I am trying to write a function that does the reverse.</p>
  
  <p>When I know how many cases this can be done as follows:</p>
  
  <pre class="lang-r prettyprint-override"><code>combine_indices = function(db, cols, vals){
    db %&gt;% mutate(new_col = case_when(!!sym(cols[1]) == 1 ~ vals[1],
                                      !!sym(cols[2]) == 1 ~ vals[2],
                                      !!sym(cols[3]) == 1 ~ vals[3]))
  }
  
  cols = c("g2", "g3", "g4")
  vals = c(2,3,4)
  combine_indices(mtcars, cols, vals)
  </code></pre>
  
  <p>However, I would like the <code>combine_indices</code> function to handle any number of index columns (right now it works for exactly three).</p>
  
  <p>According to the documentation (<code>?case_when</code>), "if your patterns are stored in a list, you can splice that in with <code>!!!</code>". But I can not get this working:</p>
  
  <pre class="lang-r prettyprint-override"><code>patterns = list(sym(cols[1] == 1 ~ vals[1],
                  sym(cols[2] == 1 ~ vals[2],
                  sym(cols[3] == 1 ~ vals[3])
  
  mtcars %&gt;% mutate(new_col = case_when(!!!patterns))
  </code></pre>
  
  <p>Only produces a new column filled with NAs.</p>
  
  <p>If <code>!!!patterns</code> worked, then it would be straightforward to take the lists <code>cols</code> and <code>vals</code> and generate <code>patterns</code>. However, I can not get the quosures correct. Hoping someone more familiar with quosures knows how.</p>
  
  <p>Note - some similar questions here of SO were solved using joins or other functions. <strong>However, I am restricted to using <code>case_when</code></strong> because of how it translates to sql when using dbplyr.</p>