R Delete Data Frame Rows where All or Some Values are Missing (2 Examples)
In this R tutorial you’ll learn how to drop NA rows of a data frame.
Creation of Exemplifying Data
my_df <- data.frame(x = 1:10, # Creating some example data y = letters[1:10]) my_df$x[c(3, 5, 10)] <- NA # Inserting missing values my_df$y[c(3, 4)] <- NA my_df # Returning example data to RStudio console # x y # 1 1 a # 2 2 b # 3 NA <NA> # 4 4 <NA> # 5 NA e # 6 6 f # 7 7 g # 8 8 h # 9 9 i # 10 NA j |
my_df <- data.frame(x = 1:10, # Creating some example data y = letters[1:10]) my_df$x[c(3, 5, 10)] <- NA # Inserting missing values my_df$y[c(3, 4)] <- NA my_df # Returning example data to RStudio console # x y # 1 1 a # 2 2 b # 3 NA <NA> # 4 4 <NA> # 5 NA e # 6 6 f # 7 7 g # 8 8 h # 9 9 i # 10 NA j
Example 1: Delete Rows Were All Values Are Missing
my_df[!is.na(my_df$x), ] # Applying is.na function # x y # 1 1 a # 2 2 b # 4 4 <NA> # 6 6 f # 7 7 g # 8 8 h # 9 9 i |
my_df[!is.na(my_df$x), ] # Applying is.na function # x y # 1 1 a # 2 2 b # 4 4 <NA> # 6 6 f # 7 7 g # 8 8 h # 9 9 i
Example 2: Delete Rows Were At Least One Value Is Missing
na.omit(my_df) # Applying na.omit function # x y # 1 1 a # 2 2 b # 6 6 f # 7 7 g # 8 8 h # 9 9 i |
na.omit(my_df) # Applying na.omit function # x y # 1 1 a # 2 2 b # 6 6 f # 7 7 g # 8 8 h # 9 9 i