Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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?

like image 967
Ljupcho Naumov Avatar asked Jan 26 '26 08:01

Ljupcho Naumov


1 Answers

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
like image 184
stefan Avatar answered Jan 28 '26 21:01

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!