How to Drop Data Frame Rows with NaN Values in R (Example Code)

In this tutorial you’ll learn how to remove data frame rows containing NaN values in R programming.

Creation of Example Data

data(iris)                           # Construct example data
my_iris <- head(iris)
my_iris$Sepal.Length[c(1, 3, 5)] <- NaN
my_iris$Sepal.Width[c(1, 2)] <- NaN
my_iris                              # Display example data in RStudio console
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          NaN         NaN          1.4         0.2  setosa
# 2          4.9         NaN          1.4         0.2  setosa
# 3          NaN         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          NaN         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example: Drop Rows with NaN Values Using the na.omit() Function

na.omit(my_iris)                     # Remove NaN rows
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 4          4.6         3.1          1.5         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top