title: Conditional pasting of values from different columns in R (ignoring NAs)
body: <p>I have a dataset of patients with certain disorders (<code>Diag_main</code>). Some of these disorders have subcategorical diagnosis (<code>Diag_subgroup_CBS</code> or <code>Diag_subgroup_PPA</code>). For example, individuals with values =CBS in <code>Diag_main</code> will have corresponding Type 1 or Type 2 values (in <code>Diag_subgroup_CBS</code>) and individuals with values=PPA in <code>Diag_main</code> will have PPA-A or PPA-B.</p>
  <p>Example data:</p>
  <pre class="lang-r prettyprint-override"><code>df&lt;-data.frame(
    id=c(1:7), 
    Diag_main=c('BBA', 'CBS', 'PPA', 'AM', 'CBS', 'PPA', 'BBA'), 
    Diag_subgroup_CBS=c(NA, '0', NA, NA, '1', NA, NA), 
    Diag_subgroup_PPA=c(NA, NA, '0', NA, NA, NA, '1')
  )
  </code></pre>
  <p><strong>What I'm looking for:</strong></p>
  <p>I want to create a new column (<code>Diag_combined</code>) that (i) for CBS: recodes 0 as Type1 and 1 as Type2, (ii) for PPA: recodes 0 as PPA-A and 1 as PPA-B, (iii) for individuals with CBS or PPA, pastes their Subgroup value, (i.e., Type1, PPA-A etc.) and (ii) for individuals without CBS or PPA, pastes their <code>Diag_main</code> value.</p>
  <pre class="lang-r prettyprint-override"><code>df2&lt;-data.frame(
    id=c(1:7), 
    Diag_main=c('BBA', 'CBS', 'PPA', 'AM', 'CBS', 'PPA', 'BBA'), 
    Diag_subgroup_CBS=c(NA, '0', NA, NA, '1', NA, NA), 
    Diag_subgroup_PPA=c(NA, NA, '0', NA, NA, NA, '1'), 
    Diag_combined=c('BBA', 'Type1', 'PPA-A', 'AM', 'Type2', 'PPA-B', 'BBA')
  )
  </code></pre>
  <p>I tried doing this using <code>dplyr::mutate</code> using this code:</p>
  <pre class="lang-r prettyprint-override"><code>df3 &lt;- mutate(df,
    Diag_combined=ifelse(grepl('0', Diag_subgroup_CBS), 'Type1', 
                         ifelse(grepl('1', Diag_subgroup_CBS), 'Type2',  
                                ifelse(grepl('0', Diag_subgroup_PPA), 'PPA-A', 
                                       ifelse(grepl('1', Diag_subgroup_PPA), 'PPA-B', Diag_main))))))
  </code></pre>
  <p>When I run this, I get errors stating <code>Problem with 'mutate()' column 'Diag_combined'. The error occurred in Diag_combined: id = 1.</code>. I don't know if this is because <code>dplyr::mutate</code> is not ignoring NAs.</p>
  <p>I don't understand why this code is not working. What's the fastest and most efficient way to do this?</p>