Ljupcho Naumov
Ljupcho Naumov

Reputation: 465

Referring to columns and variables with the same name in dplyr filter

given this situation

id = "a"

df <- tibble(
  id = c("a", "b", "c"),
  value = c(1, 2, 3)
)

df %>% dplyr::filter(id == id)

I expected the last line to have the same output as df %>% dplyr::filter(id == "a") but it still refers to id as a df column and not as a variable. Can I enforce it to look for the variable id?

Upvotes: 11

Views: 1317

Answers (1)

stefan
stefan

Reputation: 124213

This could be achieved via the .env pronoun from rlang:

See e.g. this blog post.

library(dplyr)

id = "a"

df <- tibble(
  id = c("a", "b", "c"),
  value = c(1, 2, 3)
)

df %>% 
  dplyr::filter(id == .env$id)
#> # A tibble: 1 × 2
#>   id    value
#>   <chr> <dbl>
#> 1 a         1

Upvotes: 15

Related Questions