简体   繁体   中英

How to remove rows Inf from a specific column in a dataframe using Tidyverse in R?

I have a dataframe and I want to remove rows with Inf values present in a selected column. I'm looking for a solution using tidyverse as I want to include it into my tidyverse pipes.

Example:

df <- data.frame(a = c(1, 2, 3, NA), b = c(5, Inf, 8, 8), c = c(9, 10, Inf, 11), d = c('a', 'b', 'c', 'd'))

I want to remove rows having Inf values in column c . The result would be:

df2 <- data.frame(a = c(1, 2, NA), b = c(5, Inf, 8), c = c(9, 10, 11), d = c('a', 'b', 'd'))

I wish there was a function something like drop_inf() , similar to drop_na() .

EDIT: The column name is passed as a variable.

You can use is.finite

df %>%
  filter(is.finite(c))

   a   b  c d
1  1   5  9 a
2  2 Inf 10 b
3 NA   8 11 d

If you want to have a dynamic column, you can use {{ }} :

my_fun <- function(df, filter_col){
  df %>%
  filter(is.finite({{filter_col}}))
}

my_fun(df, b)
my_fun(df, c)

This way you can work dynamically with my_fun like with other dplyr verbs. For example:

df %>% select(a:c) %>% my_fun(c)

See also this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM