Replace Blank by NA in R DataFrame
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
data = data.frame (col1 = c (1, 2, 3, "" ),
col2 = c ( "" , 4, 5, "" ))
final = data
final[final == "" ] <- NA
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
data = data.frame (col1 = c (1, 2, 3, " " ),
col2 = c ( " " , 4, 5, " " ))
final = data
final[final == " " ] <- NA
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
data = data.frame (col1 = c (1, 2, 3, "" ),
col2 = c ( "" , 4, " " , " " ))
final = data
final[final == "" | final== " " ] <- NA
print (final)
|
Output:
col1 col2
1 1 <NA>
2 2 4
3 3 <NA>
4 <NA> <NA>
Last Updated :
23 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...