R Replace NA with Blank in Data Frame Columns (Example Code)

In this tutorial, I’ll explain how to exchange missing data with blank character values in the R programming language.

Creating Example Data

data(iris)                                    # Load and modify iris data
iris_new <- iris
iris_new$Sepal.Width[c(1, 3, 4)] <- NA
iris_new$Petal.Length[c(2, 4)] <- NA
iris_new$Species[c(2, 3, 6)] <- NA
head(iris_new)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1          NA          1.4         0.2  setosa
# 2          4.9         3.0           NA         0.2    <NA>
# 3          4.7          NA          1.3         0.2    <NA>
# 4          4.6          NA           NA         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4    <NA>

Example: Set NA to Blank in All Data Frame Variables

iris_new <- sapply(iris_new, as.character)    # Set class of all columns to character
iris_new[is.na(iris_new)] <- ""               # Exchange NA by blank characters
head(iris_new)                                # Show new data frame in RStudio console
#      Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
# [1,] "5.1"        ""          "1.4"        "0.2"       "setosa"
# [2,] "4.9"        "3"         ""           "0.2"       ""      
# [3,] "4.7"        ""          "1.3"        "0.2"       ""      
# [4,] "4.6"        ""          ""           "0.2"       "setosa"
# [5,] "5"          "3.6"       "1.4"        "0.2"       "setosa"
# [6,] "5.4"        "3.9"       "1.7"        "0.4"       ""

Leave a Reply

Your email address will not be published.

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