Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Replace Inf with NA in Dataframe in R

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:


My Personal Notes arrow_drop_up
Last Updated : 27 Sep, 2021
Like Article
Save Article
Similar Reads
Related Tutorials