Efficient method to subset drop rows with NA values in R

dataframe, indexing, na, r, subset

Solution

Let `dat` be a data frame and `cols` a vector of column names or column numbers of interest. Then you can use

dat[!rowSums(is.na(dat[cols])), ]

to exclude all rows with at least one `NA`.

Problem

Background Before running a stepwise model selection, I need to remove missing values for any of my model terms. With quite a few terms in my model, there are therefore quite a few vectors that I need to look in for NA values (and drop any rows that have NA values in any of those vectors). However, there are also vectors that contain NA values that I do not want to use as terms / criteria for dropping rows. Question How do I drop rows from a dataframe which contain NA values for any of a list of vectors? I'm currently using the clunky method of a long series of !is.na's ``` > my.df[!is.na(my.df$termA)&!is.na(my.df$termB)&!is.na(my.df$termD),] ``` but I'm sure that there is a more elegant method.

Original source