3

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'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
spore234
  • 3,550
  • 6
  • 50
  • 76
  • 4
    You need `get` , `df %>% filter(str_detect(get(var), 'aa'))`. In fact, you were very close with `eval(parse(..`, You needed `df %>% filter(str_detect(eval(parse(text = var)), 'aa'))` – Ronak Shah Jul 31 '18 at 07:32

0 Answers0