Filter any rows that contain Inf

Viewed 125

I am trying to debug and check why some rows on a data frame contain Inf values.

blah <- data.frame(
    x = 1:10,
    y = c(1:7,Inf,9:10),
    z = c(Inf, 2:10)
    )

Tried:

blah %>% filter_if(is.infinite)
Error in selected[[i]] <- eval_tidy(.p(column, ...)) : 
  more elements supplied than there are to replace

Desired result is a new data frame with the rows that contain Inf values, in the case of blah, rows 1 and 8.

How can I filter a data frame to return all rows where any of them contain Inf?

5 Answers

I am not sure if the code below works for you

subset(blah,is.infinite(rowMeans(blah)))

giving

  x   y   z
1 1   1 Inf
8 8 Inf   8

You can also do it with tidyverse:

blah %>% rowwise %>% filter(any(is.infinite(c_across(where(is.numeric)))))

which produces:

# A tibble: 2 x 3
# Rowwise: 
      x     y     z
  <int> <dbl> <dbl>
1     1     1   Inf
2     8   Inf     8

Using the new across syntax, I think the most direct way would be

blah %>% filter(across(everything(), is.infinite) %>% purrr::reduce(`|`))

The reduce here checks if any of the columns are infinite rather than all of the columns. If you wanted the opposite selection, its a bit easier with just

blah %>% filter(across(everything(), is.finite))

An option with Reduce and lapply in base R

blah[Reduce(`|`, lapply(blah, is.infinite)),]
#  x   y   z
#1 1   1 Inf
#8 8 Inf   8

Another dplyr approach would be:

library(dplyr)
#Code
blah %>% 
  filter(apply(., 1, function(row) any(is.infinite(row))))

Output:

  x   y   z
1 1   1 Inf
2 8 Inf   8
Related