Replace Inf with NA in Dataframe in R
Last Updated :
27 Sep, 2021
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
data= data.frame (column1 = c ( Inf , 2, 3, 4, 5),
column2 = c (1, Inf , 1, Inf , 1),
column3 = c (1,2,3, Inf , Inf ))
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
data= data.frame (column1 = c ( Inf , 2, 3, 4, 5),
column2= c (1, Inf , 1, Inf , 1),
column3= c (1,2,3, Inf , Inf ))
print (data)
final= do.call (data.frame, lapply
(data, function (value) replace
(value, is.infinite (value), NA )))
print (final)
|
Output:
Example 2:
R
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 ))
print (data)
final= do.call (data.frame,lapply
(data, function (value) replace
(value, is.infinite (value), NA )))
print (final)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...