Doug Fir
Doug Fir

Reputation: 21232

Filter any rows that contain Inf

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?

Upvotes: 2

Views: 685

Answers (5)

akrun
akrun

Reputation: 887183

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

Upvotes: 1

MrFlick
MrFlick

Reputation: 206243

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))

Upvotes: 2

Duck
Duck

Reputation: 39595

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

Upvotes: 1

mysteRious
mysteRious

Reputation: 4294

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

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101628

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

Upvotes: 3

Related Questions