Remove rows which have all NAs in certain columns

后端 未结 5 1695
面向向阳花
面向向阳花 2020-12-11 08:08

Suppose you have a dataframe with 9 columns. You want to remove cases which have all NAs in columns 5:9. It\'s not at all relevant if there are NAs in columns 1:4.

S

5条回答
  •  萌比男神i
    2020-12-11 08:29

    Here are two dplyr options:

    library(dplyr)
    df <- data_frame(a = c(0, NA, 0, 4, NA, 0, 6), b = c(1, NA, 0, 4, NA, 0, NA), c = c(1, 0, 1, NA, NA, 0, NA))
    
    
    # columns b and c would be the columns you don't want all NAs
    
    df %>% 
      filter_at(vars(b, c), any_vars(!is.na(.)))
    
    df %>% 
      filter_at(vars(b, c), any_vars(complete.cases(.)))
    
    # A tibble: 5 x 3
          a     b     c
        
    1     0     1     1
    2    NA    NA     6
    3     0     6     1
    4     4     4    NA
    5     0     0     0
    

提交回复
热议问题