How to Delete Empty Rows of Data File in R Programming (2 Examples)

In this article, I’ll illustrate how to delete rows where all data cells are empty in the R programming language.

Example 1: Delete Rows where All Cells are Empty

data_empty <- data.frame(var1 = c("5", "1", "", "7", "3"),  # Data frame with empty cells
                         var2 = c("C", "C", "", "D", ""))
data_empty                                                  # Show data
#   var1 var2
# 1    5    C
# 2    1    C
# 3          
# 4    7    D
# 5    3
data_empty[!apply(data_empty == "", 1, all), ]              # Delete rows with only empty cells
#   var1 var2
# 1    5    C
# 2    1    C
# 4    7    D
# 5    3

Example 2: Delete Rows where All Cells are Missing (i.e. NA)

data_NA <- data.frame(var1 = c(6, 2, NA, NA, 3),            # Data frame with NAs
                      var2 = c("F", "X", NA, "P", "Y"))
data_NA                                                     # Show data
#   var1 var2
# 1    6    F
# 2    2    X
# 3   NA <NA>
# 4   NA    P
# 5    3    Y
data_NA[rowSums(is.na(data_NA)) != ncol(data_NA), ]         # Delete rows with only NAs
#   var1 var2
# 1    6    F
# 2    2    X
# 4   NA    P
# 5    3    Y

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top