delete rows that contain NAs in certain columns R

dataframe, r

Solution

You can still use `complete.cases()`. Just apply it to the desired columns (columns 1:4 in the example below) and then use the Boolean vector it returns to select valid rows from the entire data.frame.

set.seed(4)
x <- as.data.frame(replicate(6, sample(c(1:10,NA))))
x[complete.cases(x[1:4]),]
#    V1 V2 V3 V4 V5 V6
# 1   7  4  6  8 10  5
# 2   1  2  5  5  1  2
# 5   6  8  4 10  6  6
# 6   2  6  9  3  4  4
# 7   4  3  3  1  2  1
# 9   8  5  2  7  7  3
# 10 10 10  1  2  5 NA

Problem

I have a data.frame that contains many columns. I want to keep the rows that have no NAs in 4 of these columns. The complication arises from the fact that I have other rows that are allowed have NAs in them so I can't use complete.cases or is.na. What's the most efficient way to do this?

Original source