Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Replace Blank by NA in R DataFrame

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we are going to see how to replace Blank space with NA in dataframe in R Programming Language.

Example 1: R program to replace blank by NA in dataframe

We will replace the empty cells using a logical condition based on the “==” operator.

Syntax:

dataframe[dataframe == “”] <- NA

R




# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 = c(1, 2, 3, ""),
                  col2 = c("", 4, 5, ""))
  
# store actual dataframe in final
final = data
  
# replace blank with NA
final[final == ""] <- NA 
  
# display final dataframe
print(final)

Output:

  col1 col2
1    1 <NA>
2    2    4
3    3    5
4 <NA> <NA>

Example 2: R program to replace blank and space by NA in dataframe

R




# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 = c(1, 2, 3, " "),
                  col2 = c(" ", 4, 5, " "))
  
# store actual dataframe in final
final = data
  
# replace blank and space with NA
final[final == " "] <- NA 
  
# display final dataframe
print(final)

Output:

  col1 col2
1    1 <NA>
2    2    4
3    3    5
4 <NA> <NA>

Example 3: R program to replace blank and blank spaces with NA

If we want to replace both blank and blank space then we can use both the conditions separated by | operator

Syntax:

dataframe[dataframe==”” | dataframe == ” “] <- NA

R




# create a dataframe with 4 rows and 2 columns
data = data.frame(col1 =c (1, 2, 3, ""),
                  col2 = c("", 4, " ", " "))
  
# store actual dataframe in final
final = data
  
# replace blank and blank space with NA
final[final == ""  | final== " "] <- NA 
  
# display final dataframe
print(final)

Output:

  col1 col2
1    1 <NA>
2    2    4
3    3 <NA>
4 <NA> <NA>

My Personal Notes arrow_drop_up
Last Updated : 23 Sep, 2021
Like Article
Save Article
Similar Reads
Related Tutorials