Set Blank to NA in R (Example Code)

This article illustrates how to exchange blanks by NA in R programming.

Creation of Example Data

my_df <- data.frame(x = c("", LETTERS[1:4]),    # Constructing data frame in R
                   y = c(1:3, "", ""))
my_df                                           # Showing data frame in RStudio console
#   x y
# 1   1
# 2 A 2
# 3 B 3
# 4 C  
# 5 D

Example: Replacing Blank by NA in All Data Frame Columns

my_df[my_df == ""] <- NA                        # Setting blank to NA
my_df                                           # Showing new data frame
#      x    y
# 1 <NA>    1
# 2    A    2
# 3    B    3
# 4    C <NA>
# 5    D <NA>

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