2016-12-07 47 views
3

是否有一种方法可以使用dplyr的过滤器函数从数据帧中打印每个过滤器操作过滤器的行数?打印由dplyr的过滤器函数过滤的行数

考虑将其过滤的简单示例数据帧:

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

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

我想这一段代码,以输出:

  • '使用筛选出2行:!COL1 = 4'
  • '过滤出3行使用:col1!= 5'

我到目前为止尝试过创建自己的fu n

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

但是,这并没有真的帮了我。

+0

另外,看看purrr :: walk(),它将打印函数的副作用并传输数据。 –

回答

2

非常接近!你实际上在寻找关于Non-Standard Evaluation的章节。

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

一个很棒的功能。但是,虽然它在dplyr 0.4上运行,但在dplyr 0.7中不起作用。 –