 GeeksforGeeks App
Open App Browser
Continue

# 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

 `# 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>```

## 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