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

六月ゝ 毕业季﹏ 提交于 2020-04-05 15:12:28

问题


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:

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

na.omit(dat) removes all rows with an NA not just the ones where the NA is in column B.

Also I'd like to know how to this for NA value in two columns.

I appreciate all advice!


回答1:


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



回答2:


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")



回答3:


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



回答4:


This should work

dat = dat[dat['B'].notnull()]  


来源:https://stackoverflow.com/questions/48658832/how-to-remove-row-if-it-has-a-na-value-in-one-certain-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!