How to Remove Empty Rows from Data Frame in R


You can use the following methods to remove empty rows from a data frame in R:

Method 1: Remove Rows with NA in All Columns

df[rowSums(is.na(df)) != ncol(df), ]

Method 2: Remove Rows with NA in At Least One Column

df[complete.cases(df), ]

The following examples show how to use each method in practice.

Example 1: Remove Rows with NA in All Columns

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(x=c(3, 4, NA, 6, 8, NA),
                 y=c(NA, 5, NA, 2, 2, 5),
                 z=c(1, 2, NA, 6, 8, NA))

#view data frame
df

   x  y  z
1  3 NA  1
2  4  5  2
3 NA NA NA
4  6  2  6
5  8  2  8
6 NA  5 NA

We can use the following code to remove rows from the data frame that have NA values in every column:

#remove rows with NA in all columns
df[rowSums(is.na(df)) != ncol(df), ]

   x  y  z
1  3 NA  1
2  4  5  2
4  6  2  6
5  8  2  8
6 NA  5 NA

Notice that the one row with NA values in every column has been removed.

Example 2: Remove Rows with NA in At Least One Column

Once again suppose we have the following data frame in R:

#create data frame
df <- data.frame(x=c(3, 4, NA, 6, 8, NA),
                 y=c(NA, 5, NA, 2, 2, 5),
                 z=c(1, 2, NA, 6, 8, NA))

#view data frame
df

   x  y  z
1  3 NA  1
2  4  5  2
3 NA NA NA
4  6  2  6
5  8  2  8
6 NA  5 NA

We can use the following code to remove rows from the data frame that have NA values in at least one column:

#remove rows with NA in at least one column
df[complete.cases(df), ]

  x y z
2 4 5 2
4 6 2 6
5 8 2 8

Related:

The following tutorials explain how to perform other common tasks in R:

x