0

How can I tell dplyr that I want to use a placeholder, e.g. instead of a variable name contained in a dataset?

For example, if I want to filter in mtcars only those with 4 cylinders:

mtcars %>% filter(cyl == 4)

Now with a placeholder:

place_holder_variable <- "cyl"
mtcars %>% filter(place_holder_variable == 4)

However, now I get "<0 rows> (or 0-length row.names)" instead of the filtered list.

How do I have to proceed instead?

SCW16
  • 403
  • 2
  • 4
  • 10
  • 2
    use `.data`: `mtcars %>% filter(.data[[place_holder_variable]] == 4)` – det Jun 20 '22 at 11:22
  • 4
    One option is to capture "place_holder_variable" as a [symbol](https://adv-r.hadley.nz/quasiquotation.html?q=ensym#capturing-symbols) and use the 'bang-bang' operator [re non-standard evaluation](https://adv-r.hadley.nz/quasiquotation.html?q=!!#the-polite-fiction-of): `mtcars %>% filter(!!ensym(place_holder_variable) == 4)`. This is useful when creating functions, as your placeholdervariable can be quoted or unquoted e.g. https://stackoverflow.com/a/49208560/12957340 – jared_mamrot Jun 20 '22 at 11:28
  • 1
    Does this answer your question? [When to use rlang::ensym() over rlang::sym()?](https://stackoverflow.com/questions/49208497/when-to-use-rlangensym-over-rlangsym) – Len Greski Jun 20 '22 at 11:45
  • Thanks you all, all the three solutions worked! I will have a deeper look into rlang::ensym(). – SCW16 Jun 20 '22 at 15:36

1 Answers1

2

Eval-parse works for this case:

place_holder <- c("cyl")
mtcars %>% filter(eval(parse(text = place_holder)) == 4)

Sorry, I'm quite new here and do not have the rep to add this as a comment.

akshaymoorthy
  • 326
  • 1
  • 4