Last active
July 21, 2020 21:12
-
-
Save randrescastaneda/55affb202cef77e41dc4701be364518e to your computer and use it in GitHub Desktop.
How to use deparse in preparing conditions to by used in tidyverse of dplyr functions
This file contains 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) | |
# Original data | |
tb <- tibble( | |
x = c("a", "b", "c", "d"), | |
y = c(1, 2, 3, 4) | |
) | |
# Regular condition | |
tb %>% | |
filter(!(x %in% c("a", "b"))) | |
#> # A tibble: 2 x 2 | |
#> x y | |
#> <chr> <dbl> | |
#> 1 c 3 | |
#> 2 d 4 | |
# Creating the same condition based on the object `aa` | |
aa <- c("a", "b") | |
condition <- paste0('!(x %in% ', deparse(aa), ')') # The trick is in `deparse()` | |
condition | |
#> [1] "!(x %in% c(\"a\", \"b\"))" | |
# This is what should go within the function. | |
parcond <- parse(text = condition) # within the function you parse again/ | |
tb %>% | |
filter(eval(parcond)) | |
#> # A tibble: 2 x 2 | |
#> x y | |
#> <chr> <dbl> | |
#> 1 c 3 | |
#> 2 d 4 | |
#<sup>Created on 2020-07-21 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment