GeeksforGeeks App
Open App
Browser
Continue

# Replace Inf with NA in Dataframe in R

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 rowsdata=data.frame(column1 = c(Inf, 2, 3, 4, 5),                 column2 = c(1, Inf, 1, Inf, 1),                column3 = c(1,2,3,Inf,Inf)) # display dataframeprint(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.

## R

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

Output:

## R

 # create a dataframe with 5 columns and 5 rowsdata=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 dataframeprint(data) # replace inf with NAfinal=do.call(data.frame,lapply              (data, function(value) replace               (value, is.infinite(value),NA))) # displayprint(final)

Output:

My Personal Notes arrow_drop_up