VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-replace-nas-with-strings-in-r/

⇱ How to Replace NAs with Strings in R? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Replace NAs with Strings in R?

Last Updated : 28 Nov, 2021

In this article, we will discuss how to Replace NAs with strings in R Programming Language. NA stands for Not a Number, we can replace NA with strings in the dataframe.

Create Dataframe for demonestration:

Output:

 name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur

Example 1: Replace NAs with Strings in One Column

we can replace NA's with strings in particular column using replace_na() function, we have to import tidyr package

Syntax: dataframe$column_name%>% replace_na('string')

where

  1. dataframe  is the input dataframe
  2. column_name is the column replace with the string

R program to replace NAs with string in the given column

Output:

 name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur


 name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur

Example 2: Replace NAs with Strings in Multiple Columns

Here we are using the same method as above but, to replace in multiple columns we have to specify multiple columns in a list function

Syntax: dataframe %>% replace_na(list(column1 = 'string', column2 = 'string',.,columnn = 'string',))

Output:

 name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur


 name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur
Comment

Explore