18.4 C
London
Saturday, July 19, 2025
HomeStatistics TutorialRHow to Remove Empty Rows from Data Frame in R

How to Remove Empty Rows from Data Frame in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 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 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

Notice that all rows with an NA value in at least one column have been removed.

Related: How to Use complete.cases in R (With Examples)

Additional Resources

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

How to Create an Empty Data Frame in R
How to Create an Empty List in R
How to Create an Empty Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories