R How to Delete Data Frame Rows with NA Using dplyr Package (3 Examples)
In this R tutorial you’ll learn how to extract rows with missings.
Setting up the Examples
my_df <- data.frame(col1 = c(1, NA, NA, 1, 1, 5), # Constructing data frame with NA col4 = c(letters[1:5], NA), col2 = c("Ya", NA, "Yo", "Yi", "Ye", NA), col3 = 22, col5 = 9:4) my_df # Showing example data in RStudio console # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 2 NA b <NA> 22 8 # 3 NA c Yo 22 7 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5 # 6 5 <NA> <NA> 22 4 |
my_df <- data.frame(col1 = c(1, NA, NA, 1, 1, 5), # Constructing data frame with NA col4 = c(letters[1:5], NA), col2 = c("Ya", NA, "Yo", "Yi", "Ye", NA), col3 = 22, col5 = 9:4) my_df # Showing example data in RStudio console # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 2 NA b <NA> 22 8 # 3 NA c Yo 22 7 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5 # 6 5 <NA> <NA> 22 4
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr
Example 1: Deleting Data Frame Rows Containing NA in Certain Variable
my_df %>% filter(!is.na(col1)) # Remove rows with NA in col1 # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 2 1 d Yi 22 6 # 3 1 e Ye 22 5 # 4 5 <NA> <NA> 22 4 |
my_df %>% filter(!is.na(col1)) # Remove rows with NA in col1 # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 2 1 d Yi 22 6 # 3 1 e Ye 22 5 # 4 5 <NA> <NA> 22 4
Example 2: Deleting Data Frame Rows Containing NA in Any Variable Using na.omit
my_df %>% na.omit # Remove rows with at least one NA # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5 |
my_df %>% na.omit # Remove rows with at least one NA # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5
Example 3: Deleting Data Frame Rows Containing NA in Any Variable Using filter & complete.cases
my_df %>% filter(complete.cases(.)) # Remove rows with at least one NA # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5 |
my_df %>% filter(complete.cases(.)) # Remove rows with at least one NA # col1 col4 col2 col3 col5 # 1 1 a Ya 22 9 # 4 1 d Yi 22 6 # 5 1 e Ye 22 5
Related Articles
Below, you may find some further resources on topics such as variables and dplyr: