R: data.table count !NA per row : <p>I am trying to count the number of columns that do not contain NA for each row, and place that value into a new column for that row.</p>

<p>Example data:</p>

<pre><code>library(data.table)

a = c(1,2,3,4,NA)
b = c(6,NA,8,9,10)
c = c(11,12,NA,14,15)
d = data.table(a,b,c)

&gt; d 
    a  b  c
1:  1  6 11
2:  2 NA 12
3:  3  8 NA
4:  4  9 14
5: NA 10 15
</code></pre>

<p>My desired output would include a new column <code>num_obs</code> which contains the number of non-NA entries per row:</p>

<pre><code>    a  b  c num_obs
1:  1  6 11       3
2:  2 NA 12       2
3:  3  8 NA       2
4:  4  9 14       3
5: NA 10 15       2
</code></pre>

<p>I've been reading for hours now and so far the best I've come up with is looping over rows, which I know is never advisable in R or data.table.  I'm sure there is a better way to do this, please enlighten me.</p>

<p>My crappy way:</p>

<pre><code>len = (1:NROW(d))
for (n in len) {
  d[n, num_obs := length(which(!is.na(d[n])))]
}
</code></pre>
