Use variable names in functions of dplyr

In the newer versions, we can use we can create the variables as quoted and then unquote (UQ or !!) for evaluation

var <- quo(color)
filter(df, UQ(var) == "blue")
#   color value
#1  blue     1
#2  blue     3
#3  blue     4

Due to operator precedence, we may require () to wrap around !!

filter(df, (!!var) == "blue")
#   color value
#1  blue     1
#2  blue     3
#3  blue     4

With new version, || have higher precedence, so

filter(df, !! var == "blue")

should work (as @Moody_Mudskipper commented)

Older option

We may also use:

 filter(df, get(var, envir=as.environment(df))=="blue")
 #color value
 #1  blue     1
 #2  blue     3
 #3  blue     4

EDIT: Rearranged the order of solutions

Leave a Comment