6 C
London
Tuesday, March 11, 2025
HomeStatistics TutorialRHow to Replace Blanks with NA in R (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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==""] 

Method 2: Replace Blanks with NA in All Columns

library(dplyr)

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 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==""] #view updated data frame
df

  team position points
1    A        G     33
2    B          28
3             F     31
4    D        F     39
5    E          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 % mutate_all(na_if,"")

#view updated data frame
df

  team position points
1    A        G     33
2    B          28
3         F     31
4    D        F     39
5    E          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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories