简体   繁体   English

如何使用 R 中的 Tidyverse 从 dataframe 中的特定列中删除行 Inf?

[英]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.我有一个 dataframe,我想删除所选列中存在 Inf 值的行。 I'm looking for a solution using tidyverse as I want to include it into my tidyverse pipes.我正在寻找使用 tidyverse 的解决方案,因为我想将它包含到我的 tidyverse 管道中。

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 .我想删除c列中具有 Inf 值的行。 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() .我希望有一个 function 类似于drop_inf() ,类似于drop_na()

EDIT: The column name is passed as a variable.编辑:列名作为变量传递。

You can use is.finite你可以使用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.这样,您可以像使用其他dplyr动词一样动态地使用my_fun For example:例如:

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

See also this question .另请参阅此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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