Open In App

How to remove empty rows from R dataframe?

Last Updated : 26 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A dataframe can contain empty rows and here with empty rows we don’t mean NA, NaN or 0, it literally means empty with absolutely no data. Such rows are obviously wasting space and making data frame unnecessarily large. This article will discuss how can this be done.

To remove rows with empty cells we have a syntax in the R language, which makes it easier for the user to remove as many numbers of empty rows in the data frame automatically.

Syntax:

data <- data[!apply(data == “”, 1, all),]

Approach

  • Create dataframe
  • Select empty rows
  • Remove those rows
  • Copy the resultant dataframe
  • Display dataframe

Example 1:

R




gfg <- data.frame(a=c('i','','iii','iv','','vi','','viii','','x'),
                  b=c('I','','III','IV','','VI','','VIII','','X'), 
                  c=c('1','','3','4','','6','','8','','10'), 
                  d=c('a','','c','d','','f','','h','','j'))
  
print('Original dataframe:-')
gfg
  
gfg <- gfg[!apply(gfg == "", 1, all),]
print('Modified dataframe:-')
gfg


Output:

Example 2:

R




gfg <- data.frame( A=c('a','','c','','e'),
                   B=c('5','','5','','5'),
                   C=c('1','','1','','1'),
                   D=c('3','','3','','3'),
                   E=c('#','','#','','#'),
                   F=c('@','','@','','@'),
                   H=c('8','','8','','8'))
                     
print('Original dataframe:-')
gfg
  
gfg <- gfg[!apply(gfg == "", 1, all),]
print('Modified dataframe:-')
gfg


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads