I have a data frame like this:
library(tidyverse)
df <- data.frame(v1 = rnorm(5),
v2 = c('aa', 'bb', 'cc', 'aa', 'ee'))
I want to filter the rows where v2
== 'aa'. This is easy with dplyr and str_detect
from the stringr package
df %>% filter(str_detect(v2, 'aa'))
However, I am having trouble integrating this into a workflow where the column name of v2
changes.
so the column name is stored as a string and is parsed to filter, but it doesn't work:
var <- 'v2'
df %>% filter(str_detect(var, 'aa'))
I tried combinations of eval
and parse
but it doesn't work either
df %>% filter(str_detect(parse(var), 'aa'))
df %>% filter(str_detect(eval(var), 'aa'))
df %>% filter(str_detect(eval(parse(var)), 'aa'))