Created
April 27, 2018 08:39
-
-
Save tmasjc/e8f808f219a25c87b74ac23b0ddfeadb to your computer and use it in GitHub Desktop.
do filtering in tidy eval manner.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(tidyverse) | |
| set.seed(1122) | |
| vecs <- lapply(X = 1:2, function(x) rep(c(1, 2, 3), times = 10) %>% sample() %>% head(10)) | |
| names(vecs) <- paste0("col_", 1:2) | |
| dat <- vecs %>% as.data.frame() | |
| dat | |
| # Which col has repeated value more than 3 appearances? | |
| more_than_3 <- function(df, var){ | |
| var <- rlang::sym(var) | |
| df %>% | |
| group_by(!!var) %>% | |
| summarise(n = n()) %>% | |
| filter(n > 3) %>% | |
| pull(!!var) %>% | |
| range() | |
| } | |
| cols_name <- c("col_1", "col_2") | |
| some_range <- purrr::map(cols_name, more_than_3, df = dat) | |
| names(some_range) <- cols_name | |
| some_range | |
| # Ordinary method | |
| dat %>% | |
| filter(col_1 <= some_range[["col_1"]][2], | |
| col_2 <= some_range[["col_2"]][2]) | |
| # Tidy eval method | |
| my_filter <- function(df, cols){ | |
| fp <- map(cols, ~quo((!!(as.name(.))) < some_range[[.]][2])) | |
| print(fp) | |
| filter(df, !!!fp) | |
| } | |
| my_filter(dat, list("col_1", "col_2")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment