title: R ifelse(apply(max)) with one,both, or no NA's involved
body: <p>I have a data set that's liberally populated with missing values.  I'm trying to make some of them go away by finding the max of two columns.  So my data set looks like this:</p>
  
  <pre><code>df1 &lt;- data.frame(id = 1:20, col1 = runif(20)*100, col2 = runif(20)*100)
  
  df1[c(1,3,7,12,18),'col1'] &lt;- NA
  df1[c(2,4,7,14,18),'col2'] &lt;- NA
  
  &gt; head(df1,10)
     id     col1      col2
  1   1       NA 71.073951
  2   2 20.51551        NA
  3   3       NA 14.308692
  4   4 82.31036        NA
  5   5 15.89198 44.190152
  6   6 82.72071 20.761311
  7   7       NA        NA
  8   8 87.80027  8.615998
  9   9 26.98488 90.835827
  10 10 14.61701  5.184187
  </code></pre>
  
  <p>After much trial and error I've found the only way to find the <code>max</code> of the 2 columns and handle the <code>NA's</code> is a nested <code>ifelse</code> statement:</p>
  
  <pre><code>df1$col3 &lt;- NA
  df1$col3 &lt;- ifelse(is.na(df1$col1) &amp; is.na(df1$col2), NA, ifelse(!is.na(df1$col1) &amp; is.na(df1$col2), df1$col1
              ,ifelse(is.na(df1$col1) &amp; !is.na(df1$col2), df1$col2
              ,ifelse(!is.na(df1$col1) &amp; !is.na(df1$col2), apply(df1[,c('col1','col2')],1,max), df1$col3)))
              )
  </code></pre>
  
  <p>which gives:</p>
  
  <pre><code>&gt; df1
     id     col1      col2     col3
  1   1       NA 71.073951 71.07395
  2   2 20.51551        NA 20.51551
  3   3       NA 14.308692 14.30869
  4   4 82.31036        NA 82.31036
  5   5 15.89198 44.190152 44.19015
  6   6 82.72071 20.761311 82.72071
  7   7       NA        NA       NA
  8   8 87.80027  8.615998 87.80027
  9   9 26.98488 90.835827 90.83583
  10 10 14.61701  5.184187 14.61701
  </code></pre>
  
  <p>These seems overly complex.  Does anyone have a better solution?</p>