Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit rows with NA in only two columns in R?

Tags:

r

na

I want to omit rows where NA appears in both of two columns.

I'm familiar with na.omit, is.na, and complete.cases, but can't figure out how to use these to get what I want. For example, I have the following dataframe:

(df <- structure(list(x = c(1L, 2L, NA, 3L, NA),
                     y = c(4L, 5L, NA, 6L, 7L),
                     z = c(8L, 9L, 10L, 11L, NA)),
                .Names = c("x", "y", "z"),
                class = "data.frame",
                row.names = c(NA, -5L)))
x   y   z
1   4   8
2   5   9
NA  NA  10
3   6   11
NA  7   NA

and I want to remove only those rows where NAappears in both the x and y columns (excluding anything in z), to give

x   y   z
1   4   8
2   5   9
3   6   11
NA  7   NA

Does anyone know an easy way to do this? Using na.omit, is.na, or complete.cases is not working.

like image 806
Thomas Avatar asked Aug 05 '14 17:08

Thomas


People also ask

How do I ignore rows with NA in R?

By using na. omit() , complete. cases() , rowSums() , and drop_na() methods you can remove rows that contain NA ( missing values) from R data frame.

How do I omit Na variable in R?

First, if we want to exclude missing values from mathematical operations use the na. rm = TRUE argument. If you do not exclude these values most functions will return an NA . We may also desire to subset our data to obtain complete observations, those observations (rows) in our data that contain no missing data.

How do I exclude missing data in R?

Firstly, we use brackets with complete. cases() function to exclude missing values in R. Secondly, we omit missing values with na. omit() function.


1 Answers

dplyr solution

require("dplyr")
df %>% filter_at(.vars = vars(x, y), .vars_predicate = any_vars(!is.na(.)))

can be modified to take any number columns using the .vars argument


Update: dplyr 1.0.4

df %>%
  filter(!if_all(c(x, y), is.na))

See similar answer: https://stackoverflow.com/a/66136167/6105259

like image 98
pyg Avatar answered Sep 23 '22 07:09

pyg