Drop rows with missing values in R (Drop null values – NA,NaN)

Drop rows with missing values in R is done in multiple ways like using na.omit() and complete.cases() function. Let’s see how to

  • drop rows with missing values in R (Drop NA, Drop NaN)
  • drop rows with null values in R

with an Example for each.

Let’s first create the dataframe

df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa',''), 
                 Mathematics_score=c(45,78,44,89,66,NaN,72,87),
                 Science_score=c(56,52,NA,88,33,90,47,76))
df1

dataframe will be

Drop rows with missing values in R 1

 

Drop rows with missing values in R (Drop NA, Drop NaN) :

Method 1

Using na.omit() to remove (missing) NA and NaN values

df1_complete <- na.omit(df1) # Method 1 - Remove NA
df1_complete

so after removing NA and NaN the resultant dataframe will be

Drop rows with missing values in R 2

Method 2

Using complete.cases() to remove (missing) NA and NaN values

df1[complete.cases(df1),]

so after removing NA and NaN the resultant dataframe will be

Drop rows with missing values in R 3

 

Removing Both Null and missing:

By subsetting each column with non NAs and not null is round about way to remove both Null and missing values as shown below

# Remove null  & NA values
df1[!(is.na(df1$Name) | df1$Name=="" | is.na(df1$Science_score) | df1$Science_score==""|is.na(df1$Mathematics_score) | df1$Mathematics_score==""),] 

so after removing Null, NA and NaN the resultant dataframe will be

Drop rows with missing values in R 4

 

                                                                                                       

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts