How to Replace Blanks with NA in R (With Examples)


You can use the following methods to replace blanks with NA values in R:

Method 1: Replace Blanks with NA in One Column

df$my_col[df$my_col==""] <- NA

Method 2: Replace Blanks with NA in All Columns

library(dplyr)

df <- df %>% mutate_all(na_if,"")

The following examples show how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(team=c("A", "B", "", "D", "E"),
                 position=c("G", "", "F", "F", ""),
                 points=c(33, 28, 31, 39, 34))	

#view data frame
df

  team position points
1    A        G     33
2    B              28
3             F     31
4    D        F     39
5    E              34

Example 1: Replace Blanks with NA in One Column

The following code shows how to replace all blank values in the position column with NA values:

#replace all blanks in position column with NA values
df$position[df$position==""] <- NA

#view updated data frame
df

  team position points
1    A        G     33
2    B     <NA>     28
3             F     31
4    D        F     39
5    E     <NA>     34

Notice that the blank values in the position column have been replaced with NA values, while all other columns have remained unchanged.

Example 2: Replace Blanks with NA in All Columns

The following code shows how to replace the blank values in every column with NA values:

library(dplyr)

#replace blanks in every column with NA values 
df <- df %>% mutate_all(na_if,"")

#view updated data frame
df

  team position points
1    A        G     33
2    B     <NA>     28
3 <NA>        F     31
4    D        F     39
5    E     <NA>     34

Notice that the blank values in every column have been replaced with NA values.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

R: How to Replace NAs with Strings
R: How to Replace Values in Data Frame Conditionally

Leave a Reply

Your email address will not be published.