'Error when referring to column names with rlang and sym when column name is identical to passed value
What am I missing here.
I'm trying to do some data filtering based on columns that I pass into the filter function dynamically. This works as long as the column name itself is not identical to the object name in which I pass the column name:
Works:
df_a <- data.frame(x = 1:5)
df_b <- data.frame(x = 3:4)
id <- "x"
df_a |>
dplyr::filter(!!rlang::sym(id) %in% df_b[, id])
x
1 3
2 4
Doesn't work
df_a <- data.frame(id = 1:5)
df_b <- data.frame(id = 3:4)
id <- "id"
df_a |>
dplyr::filter(!!rlang::sym(id) %in% df_b[, id])
Error in `dplyr::filter()`:
! Problem while computing `..1 = id %in% df_b[, id]`.
Caused by error in `[.data.frame`:
! undefined columns selected
Run `rlang::last_error()` to see where the error occurred.
What can I do to allow passing a column name that is identical to the object name which I pass?
Update:
This one seems to work, I don't understand yet, why:
df_a |>
dplyr::filter(!!rlang::sym(id) %in% eval(rlang::sym(!!id), df_b))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
