Table of Contents
Removing empty rows from a data frame in R refers to the process of eliminating any rows that do not contain any data or have missing values. This can be achieved by using the “na.omit()” function, which removes all rows with missing values, or by using the “complete.cases()” function, which removes rows with any missing values.
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:
Cite this article
stats writer (2024). How can I remove empty rows from a data frame in R?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-i-remove-empty-rows-from-a-data-frame-in-r/
stats writer. "How can I remove empty rows from a data frame in R?." PSYCHOLOGICAL SCALES, 27 Jun. 2024, https://scales.arabpsychology.com/stats/how-can-i-remove-empty-rows-from-a-data-frame-in-r/.
stats writer. "How can I remove empty rows from a data frame in R?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-i-remove-empty-rows-from-a-data-frame-in-r/.
stats writer (2024) 'How can I remove empty rows from a data frame in R?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-i-remove-empty-rows-from-a-data-frame-in-r/.
[1] stats writer, "How can I remove empty rows from a data frame in R?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. How can I remove empty rows from a data frame in R?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
