Remove columns from dataframe where some of values are NA

前端 未结 7 1398
小鲜肉
小鲜肉 2020-11-28 08:32

I have a dataframe where some of the values are NA. I would like to remove these columns.

My data.frame looks like this

    v1   v2 
1    1   NA 
2           


        
7条回答
  •  悲哀的现实
    2020-11-28 09:17

    Alternatively, select(where(~FUNCTION)) can be used:

    library(dplyr)
    
    (df <- data.frame(x = letters[1:5], y = NA, z = c(1:4, NA)))
    #>   x  y  z
    #> 1 a NA  1
    #> 2 b NA  2
    #> 3 c NA  3
    #> 4 d NA  4
    #> 5 e NA NA
    
    # Remove columns where all values are NA
    df %>% 
      select(where(~!all(is.na(.))))
    #>   x  z
    #> 1 a  1
    #> 2 b  2
    #> 3 c  3
    #> 4 d  4
    #> 5 e NA
      
    # Remove columns with at least one NA  
    df %>% 
      select(where(~!any(is.na(.))))
    #>   x
    #> 1 a
    #> 2 b
    #> 3 c
    #> 4 d
    #> 5 e
    

提交回复
热议问题