Open In App

Replace 0 with NA in R DataFrame

In this article, we are going to discuss how to replace 0 with NA values in dataframe in R Programming Language.

NA stands for Null values which can represent Null data / Null elements in a dataframe. The task can be achieved by first defining a dataframe that contains 0 as values. Then we can replace 0 with NA by using index operator [].



Syntax:

dataframe[dataframe== 0] = NA



where,

Example: Replacing 0 with NA for integer data




# create a dataframe with 0 
# along with numeric values and display
data=data.frame(column1=c(1,2,3,0,0),
                column2=c(0,1,0,2,0))
 
# Actual data
data
 
# replace 0 with NA
data[data==0]=NA
 
print("===============")
 
# display
data

Output:

Example: R program to create a dataframe with strings along with 0 and replace 0 with NA




# create a dataframe with 0 
# along with string values and display
data=data.frame(column1=c("sravan","Bobby","ojaswi",0,0),
                column2=c(0,"Rohith",0,"Gnanesh",0))
 
# Actual data
data
 
# replace 0 with NA
data[data==0]=NA
 
print("===============")
 
# display
data

Output:


Article Tags :