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

Time:12-15

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?

CodePudding user response:

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
  • Related