Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
4 views
in R Programming by (250 points)
edited by

Want to remove the lines from data frame from that :

  • Have NAs across all columns 

             a                               b    c       d     e        f

1 YASH00000206234    0   NA   NA   NA   NA

2 YASH00000199774    0    2        2       2      2

3 YASH00000221722    0   NA   NA   NA   NA

4 YASH00000207704    0   NA   NA   1       2

5 YASH00000207531    0   NA   NA   NA   NA

6 YASH00000221412    0   1        2      3       2 

I would like to get the data frame as follows :

             a                             b    c    d    e    f

2 YASH00000199774    0   2    2    2    2

6 YASH00000221412    0   1    2    3    2 

  • Have NAs in only some columns and the result I will get:

             a                              b   c    d     e    f    

2 YASH00000199774    0   2    2    2    2

4 YASH00000207704   0  NA  NA 1   2 

6 YASH00000221412    0   1    2    3    2

2 Answers

0 votes
by
edited by

(a)To remove all rows with NA values, we use na.omit() function.

In your case:

final <- na.omit(dataframe)

Output:

             a       b    c    d    e    f

2 YASH00000199774    0    2    2    2    2

6 YASH00000221412    0    1    2    3    2

(b)To remove rows with NA by selecting particular columns from a data frame, we use complete.cases() function.

In your case:

dataframe[complete.cases(dataframe[ , 5:6]),]

Output:

              a       b   c    d     e    f    

2 YASH00000199774     0   2    2     2     2

4 YASH00000207704     0  NA    NA    1     2

6 YASH00000221412     0   1    2     3     2

If you want to explore more in R programming then watch this R programming tutorial for beginner:

0 votes
by (32.3k points)
edited by

tidyr has a new function drop_na that you can use in your case:

library(tidyr)

df %>% drop_na()

#              gene hsap mmul mmus rnor cfam

# 2 ENSG00000199674    0    2    2    2    2

# 6 ENSG00000221312    0    1    2    3    2

df %>% drop_na(rnor, cfam)

#              gene hsap mmul mmus rnor cfam

# 2 ENSG00000199674    0    2    2    2    2

# 4 ENSG00000207604    0   NA   NA    1    2

# 6 ENSG00000221312    0    1    2    3    2

Browse Categories

...