I have a dataset with over 200,000 rows and when I did summary(df), I noticed that it has Inf, in it. However, when I tried to check using any(is.na(Data) | is.infinite(Data)) I got this error
Error in is.infinite(Data) :
default method not implemented for type 'list'
I then tried to replace the Inf with NA, yet I got the same error.
>Data[is.infinite(Data)] <- NA
Error in is.infinite(Data) :
default method not implemented for type 'list'
Please is there something I am not doing right?
>Solution :
Under the hood, a data frame is a special type of list, and as the message says, is.infinite can’t be used on lists. Let’s use this example:
Data <- data.frame(a = c(1, 2, Inf), b = c(-Inf, 3, 4))
Data
#> a b
#> 1 1 -Inf
#> 2 2 3
#> 3 Inf 4
is.infinite(Data)
#> Error in is.infinite(Data): default method not implemented for type 'list'
We instead need to apply your NA replacement to each column in the data frame. We can do this quickly using
Data[] <- lapply(Data, function(x) replace(x, is.infinite(x), NA))
Data
#> a b
#> 1 1 NA
#> 2 2 3
#> 3 NA 4
An alternative that requires a bit less code would be to convert your data frame to a matrix on the fly to get the replacement indices which are applied to the data frame itself for subsetting.
Data <- data.frame(a = c(1, 2, Inf), b = c(-Inf, 3, 4))
replace(Data, is.infinite(as.matrix(Data)), NA)
#> a b
#> 1 1 NA
#> 2 2 3
#> 3 NA 4
Created on 2023-02-16 with reprex v2.0.2