How to subset rows of data frame without NA using dplyr in R?

R ProgrammingServer Side ProgrammingProgramming

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
raja
Published on 04-Aug-2021 12:46:44
Advertisements