Skip to content

Instantly share code, notes, and snippets.

@randrescastaneda
Last active July 21, 2020 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randrescastaneda/55affb202cef77e41dc4701be364518e to your computer and use it in GitHub Desktop.
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
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