title: Replace nested ifelse in data.table
body: <p>I want to create a column in my <code>data.table</code> which takes the first non <code>NA</code> value from a set of given columns:</p>
  
  <pre class="lang-r prettyprint-override"><code>library(data.table)
  o &lt;- data.table(a1 = c(1, NA, NA, NA), 
                  a2 = c(NA, 2, NA, NA), 
                  a3 = c(NA, NA, 3, NA),
                  default = 11:14)
  res &lt;- copy(o)
  res[, nc := ifelse(!is.na(a1), 
                     a1, 
                     ifelse(!is.na(a2), 
                            a2, 
                            ifelse(!is.na(a3),
                                   a3, 
                                   default)))][]
  #    a1 a2 a3 default nc
  # 1:  1 NA NA      11  1
  # 2: NA  2 NA      12  2
  # 3: NA NA  3      13  3
  # 4: NA NA NA      14 14
  </code></pre>
  
  <p>Since this becomes quite tedious with a lot of columns, I wanted to replace that by some sort of loop.
  I have read <a href="https://stackoverflow.com/questions/43045098/shorten-nested-ifelse">Shorten nested ifelse</a> and could at least get the position of the first non <code>NA</code> column via <code>max.col</code>:</p>
  
  <pre class="lang-r prettyprint-override"><code>(col_ind &lt;- o[, max.col(!sapply(.SD, is.na), "first"), .SDcol = patterns("^a|^default")])
  # [1] 1 2 3 4
  </code></pre>
  
  <p>How could I now "map" the column position to the column? With matrix subsetting I could do something like  <code>o[cbind(1:NROW(o), col_ind)]</code> but this does not work for obvious reasons? Anybody an idea how to solve that issue (no need to stick to the <code>max.col</code>  approach if there is a idomatic <code>data.table</code>solution for that?</p>