Remove rows from data.frame that contain NA values


Problem


You want to remove all rows from a data.frame that contain an NA value in any column.

 


Solution


Use this custom function to remove all rows from a data.frame that contain an NA value in any column.

# Create example data
x <- data.frame(animal=1:5, mass=c(93,NA,82,87,92), age=c(3,4,NA,NA,4))
x
 
# Define the custom function
RemoveNARow<- function(x){
  if (!inherits(x, "data.frame")) stop("X MUST BE A data.frame")
  badrow<- as.numeric()
  #Loop through each row
  for(i in 1:nrow(x)){
    #loop through each column
    for(j in 1:ncol(x)){
      if(is.na(x[i,j])==TRUE){
        #store the row for removal
        badrow<- c(badrow, i)
        break
      }#close test na
    }#close j loop
  }#close i loop
  return(x[-badrow,])
}#close function
 
 
# Employ function and save to new object
xfixed <- RemoveNARow(x)
xfixed


Notes


Dr. Shannon Albeke contributed to the development of this tool.