-1

Consider

df = data.frame(col1 = 1:3, col2 = 2:4)

I want to do

df %>%
  filter(col1 %in% 2:3)

which should return the 2nd and 3rd row, but col1 is passed in as a string as variable str_1 = "col1"

So I tried

  str_1 = "col1"
  df %>% 
    filter(!!!str_1 %in% 2:3)

  df %>% 
    filter(!!str_1 %in% 2:3)

and niether worked. What's the right syntax for this? And what's an easier way to remember these dplyr tricks?

xiaodai
  • 14,889
  • 18
  • 76
  • 140

1 Answers1

1

You can use filter_at when the you have column names as strings.

library(dplyr)
df %>% filter_at(str_1, any_vars(. %in% 2:3))
#This seems to work as well
#df %>% filter_at(str_1, ~. %in% 2:3)

#  col1 col2
#1    2    3
#2    3    4

filter_at like all other _at variants in dplyr has a .vars arguments which accepts a character vector of column names or positions to apply a function.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213