使用dplyr的filter函数过滤后被删除的行数

4

有没有办法使用dplyr的filter函数打印出每个筛选操作从数据框中筛选的行数?

考虑一个简单的示例数据框进行筛选:

test.df <- data.frame(col1 = c(1,2,3,4,4,5,5,5))

filtered.df <- test.df %>% filter(col1 != 4, col1 != 5)

我希望这段代码能够输出:
  • 使用: col1 != 4 过滤掉了2行
  • 使用: col1 != 5 过滤掉了3行
到目前为止,我尝试创建自己的函数来实现这个目标。
print_filtered_rows <- function(dataframe, ...) {
        dataframe_new <- dataframe
        for(arg in list(...)) {
            print(arg)
            dataframe <- dataframe_new
            dataframe_new <- dataframe %>% filter(arg)
            rows_filtered <- nrow(dataframe) - nrow(data_fram_new)
            print(sprintf('Filtered out %s rows using: %s', rows_filtered, arg)
        }
    return(dataframe_new)
}

但是我确实无法掌握...到底是什么以及如何使用它。我已经阅读了:http://adv-r.had.co.nz/Functions.html#function-arguments,但这并没有真正帮助我。
2个回答

4

非常接近!你实际上正在寻找关于非标准评估的章节。

library(dplyr)

print_filtered_rows <- function(dataframe, ...) {
  df <- dataframe
  vars = as.list(substitute(list(...)))[-1L]
  for(arg in vars) {
    dataframe <- df
    dataframe_new <- dataframe %>% filter(arg)
    rows_filtered <- nrow(df) - nrow(dataframe_new)
    cat(sprintf('Filtered out %s rows using: %s\n', rows_filtered, deparse(arg)))
    df = dataframe_new
  }
  return(dataframe_new)
}

data(iris)

iris %>% 
  print_filtered_rows(Species == "virginica", Species != "virginica") %>% 
  head()
#> Filtered out 100 rows using: Species == "virginica"
#> Filtered out 50 rows using: Species != "virginica"
#> [1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species     
#> <0 rows> (or 0-length row.names)

1
一个很棒的函数。然而,它在dplyr 0.4上可以运行,但在dplyr 0.7上无法运行。 - Rasmus Larsen

0
在过滤器函数中,在arg之前添加!!似乎可以修复迈克尔的好函数,如dplyr 1.0.0所示。
print_filtered_rows <- function(dataframe, ...) {
  df <- dataframe
  vars = as.list(substitute(list(...)))[-1L]
  for(arg in vars) {
    dataframe <- df
    dataframe_new <- dataframe %>% filter(!!arg)
    rows_filtered <- nrow(df) - nrow(dataframe_new)
    cat(sprintf('Filtered out %s rows using: %s\n', rows_filtered, deparse(arg)))
    df = dataframe_new
  }
  return(dataframe_new)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接