Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows with any infinite value (Inf or -Inf)

How do I subset rows from a data frame which have at least one infinite value (Inf or -Inf)?

Here is an example data frame:

my_data <- data.frame(column1 = c(Inf, 5, 3,4,5), 
                      column2 = c(1, Inf, -Inf, NA, 33))

I tried:

my_data[rowSums(is.infinite(my_data)) > 0, ]

But got the error:

Error in is.infinite(my_data) : default method not implemented for type 'list'

Which is suprising, as the is.na() equivalent works fine:

my_data[rowSums(is.na(my_data)) > 0, ]

I was able to find methods to change Inf values to NA but this is not quite what I am looking for, I only want to display all rows that contain and Inf or -Inf rather than replace them with NA.

EDIT: If there is method of doing this for a data frame with many columns, without individually typing out each column that would be ideal.

Any help would be appreciated!

like image 582
juliefoxsteven Avatar asked Oct 31 '25 19:10

juliefoxsteven


1 Answers

It seems that is.infinite cannot apply on a data.frame. An alternative is sapply:

my_data[rowSums(sapply(my_data, is.infinite)) > 0, ]

#   column1 column2
# 1     Inf       1
# 2       5     Inf
# 3       3    -Inf

With dplyr,you could use if_any or if_all to apply is.infinite to a selection of columns and combine the results into a single logical vector.

library(dplyr)

my_data %>%
  filter(if_any(where(is.numeric), is.infinite))
like image 184
Darren Tsai Avatar answered Nov 02 '25 08:11

Darren Tsai