2016-12-07 12 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) 
    

    を濾過し、簡単な例データフレームを検討 'を使用して2行を濾別:COL1を= 4'

  • 'col1!= 5'

私は今まで自分のfuを作成しようとしましたノックアウト

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では動作しません。 –

関連する問題