2016-12-07 3 views
3

dplyr의 필터 함수를 사용하여 데이터 프레임의 모든 필터 동작 필터 행 수를 인쇄 할 수 있습니까?dplyr의 필터 함수로 필터링 된 행 수 인쇄

  • : I 출력하는 코드의 부분을하고자

    test.df <- data.frame(col1 = c(1,2,3,4,4,5,5,5)) 
    
    filtered.df <- test.df %>% filter(col1 != 4, col1 != 5) 
    

    :

    여과되는 간단한 예 dataframe 고려 '를 이용하여 2 개 행을 여과! COL1를 = 4'

  • '다음을 사용하여 3 행을 필터링하여 필터링했습니다. col1! = 5'

내 자신의 fu 아무래도 ... 실제적으로 ... 실제로 무엇이며 어떻게 사용하는지 그립을 얻을 수 없습니다. 내가 읽은 :

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에서는 작동하지 않습니다. –