How to remove row if it has a NA value in one certain column

后端 未结 4 1658
无人及你
无人及你 2020-12-09 04:52

My data called \"dat\":

A   B   C
NA  2   NA
1   2   3
1   NA  3
1   2   3

I want to be all rows to be removed if it has an NA in column B:

相关标签:
4条回答
  • 2020-12-09 05:21

    The easiest solution is to use is.na():

    df[!is.na(df$B), ]
    

    which gives you:

       A B  C
    1 NA 2 NA
    2  1 2  3
    4  1 2  3
    
    0 讨论(0)
  • 2020-12-09 05:21

    try this:

    df<-data.frame(A=c(NA,1,1,1),B=c(2,2,NA,2),C=c(NA,3,3,3))
    df<-df[-which(is.na(df$B)),]
    df
       A B  C
    1 NA 2 NA
    2  1 2  3
    4  1 2  3
    
    0 讨论(0)
  • 2020-12-09 05:23

    there is an elegant solution if you use the tidyverse!

    it contains the library tidyr that provides the method drop_na which is very intuitive to read.

    So you just do:

    library(tidyverse)
    
    dat %>% drop_na("B")
    

    OR

    dat %>% drop_na(B)
    

    if B is a column name

    0 讨论(0)
  • 2020-12-09 05:44

    This should work

    dat = dat[dat['B'].notnull()]  
    
    0 讨论(0)
提交回复
热议问题