SDahm SDahm - 18 days ago 7
R Question

Set new variable NA if any other is NA

I want to add a new variable (N_notNAs) to my data frame, which defines whether any of the other variables is NA.

x y z N_notNAs
2 3 NA NA
NA 1 3 NA
2 3 5 1
4 4 3 1

Answer

Not sure why this is your desired output, but a possible way to achieve this is summing the NA per row and put it the power of NA- this way NA^0 will return 1, and everything else will become NA

NA^rowSums(is.na(df))
# [1] NA NA  1  1