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.
Example data:
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)
> d
a b c
1: 1 6 11
2: 2 NA 12
3: 3 8 NA
4: 4 9 14
5: NA 10 15
My desired output would include a new column num_obs
which contains the number of non-NA entries per row:
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
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.
My crappy way:
len = (1:NROW(d))
for (n in len) {
d[n, num_obs := length(which(!is.na(d[n])))]
}