Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows with complete.cases in more than one column in R [duplicate]

Tags:

r

Let's start with some data to make the example reproducible:

x <- structure(list(DC1 = c(5, 5, NA, 5, 4, 6, 5, NA, 4, 6, 6, 6, 
5, NA, 5, 5, 7), DC2 = c(4, 7, 4, 5, NA, 4, 6, 4, 4, 5, 5, 5, 
5, NA, 6, 5, 5), DC3 = c(4, 7, 4, 4, NA, 4, 5, 4, 5, 4, 5, 5, 
6, 4, 6, 6, 5), DC4 = c(4, 7, 5, NA, NA, 4, 6, 5, 5, 4, 3, 4, 
6, 5, 5, 6, 3), DC5 = c(7, 8, 5, NA, NA, 10, 7, 6, 8, 6, 6, 7, 
11, 10, 5, 7, 6), DC6 = c(8, 8, NA, NA, NA, 11, 9, 8, 9, 9, 10, 
10, 12, 16, 6, 8, 9), DC7 = c(10, 10, 10, NA, NA, 8, 9, 8, 13, 
8, 11, 9, 14, 13, 8, 8, 11), DC8 = c(17, 10, 10, NA, NA, 10, 
10, 10, 15, 10, 14, 11, 23, 15, 14, 13, 14), DC9 = c(16, 9, 9, 
NA, NA, 12, 13, 11, 13, 15, 15, 13, 17, 15, 25, 17, 12)), .Names = c("DC1", 
"DC2", "DC3", "DC4", "DC5", "DC6", "DC7", "DC8", "DC9"), class = "data.frame", row.names = c(NA, 
-17L))

How can I filter the data frame, keeping rows that contain data from column DC3 to DC10?

like image 375
antecessor Avatar asked Dec 16 '25 12:12

antecessor


1 Answers

Here's a dplyr option:

library(dplyr)
x %>% 
  filter_at(vars(DC3:DC9), all_vars(!is.na(.)))

or:

x %>% 
  filter_at(vars(DC3:DC9), all_vars(complete.cases(.)))

and here's a tidyr option:

x %>% tidyr::drop_na(DC3:DC9)
like image 172
sbha Avatar answered Dec 19 '25 05:12

sbha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!