I have a tibble
with column foo
that contains the name of another column in the tibble. I'd like to filter based on the column that is named in foo
:
mtcars %>%
mutate(foo = c(rep("carb", 16), rep("gear", 16))) %>%
filter(!!sym(foo) == 4)
#> Error in is_symbol(x): object 'foo' not found
It seems to be looking for foo
in the global environment, so I think I need a way to specify that foo
should be evaluated in the context of the tibble.
Desired result would be the same as running:
rbind(
mtcars[1:16,] %>% mutate(foo = "carb") %>% filter(carb == 4),
mtcars[17:32,] %>% mutate(foo = "gear") %>% filter(gear == 4)
)
#> mpg cyl disp hp drat wt qsec vs am gear carb foo
#> 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 carb
#> 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 carb
#> 3 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 carb
#> 4 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 carb
#> 5 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 carb
#> 6 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 carb
#> 7 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 carb
#> 8 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 gear
#> 9 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 gear
#> 10 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 gear
#> 11 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 gear
#> 12 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 gear