Open In App

Replace Inf with NA in Dataframe in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to replace Inf (Infinity) with NA in Dataframe in R Programming Language.

Create a dataframe with for demonstration:

R




# create a dataframe with 3 columns and 5 rows
data=data.frame(column1 = c(Inf, 2, 3, 4, 5), 
                column2 = c(1, Inf, 1, Inf, 1),
                column3 = c(1,2,3,Inf,Inf))
 
# display dataframe
print(data)


Output:

So we can replace Inf with NA by using lapply() function, we have to create our own function to replace Inf with NA and then pass that function to lapply() through do.call method.

Function Syntax:

function(value) 
replace(value, is.infinite(value), 
NA)

Where value is the input value and replace() is used to replace the value to NA if it is infinite.

Example 1: R program to replace Inf value with NA in the dataframe

R




# create a dataframe with 3 columns and 5 rows
data=data.frame(column1 = c(Inf, 2, 3, 4, 5),
                column2= c(1, Inf, 1, Inf, 1),
                column3=c(1,2,3,Inf,Inf))
 
# actual dataframe
print(data)
 
# replace inf with NA
final=do.call(data.frame, lapply
              (data, function(value) replace
               (value, is.infinite(value),NA)))
 
# display
print(final)


Output:

Example 2: 

R




# create a dataframe with 5 columns and 5 rows
data=data.frame(column1 = c(Inf, 2, 3, 4, 5),
                column2= c(1, Inf, 1, Inf, 1),
                column3=c(1,2,3,Inf,Inf),
                column4=c(Inf,Inf,Inf,3,4),
                column5=c(1,2,3,4,Inf))
 
# actual dataframe
print(data)
 
# replace inf with NA
final=do.call(data.frame,lapply
              (data, function(value) replace
               (value, is.infinite(value),NA)))
 
# display
print(final)


Output:



Last Updated : 27 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads