Subset Rows of Data Frame Without NA Using dplyr in R



To subset rows of data frame without NA using dplyr in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use filter function of dplyr package to subset the rows with !is.na.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-sample(c(NA,1,2),20,replace=TRUE)
df<-data.frame(x)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  x
1 2
2 2
3 1
4 1
5 1
6 NA
7 1
8 NA
9 NA
10 1
11 1
12 1
13 2
14 1
15 NA
16 2
17 2
18 2
19 NA
20 1

Subset the rows of data frame without NA using dplyr

Using filter function of dplyr package to subset the rows of df with !is.na as shown below −

x<-sample(c(NA,1,2),20,replace=TRUE)
df<-data.frame(x)
library(dplyr)
df %>% filter(!is.na(x))

Output

  x
1 2
2 2
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 2
11 1
12 2
13 2
14 2
15 1
Updated on: 2021-08-13T11:20:47+05:30

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements