47

I want to use variable names as strings in functions of dplyr. See the example below:

df <- data.frame( 
      color = c("blue", "black", "blue", "blue", "black"), 
      value = 1:5)
filter(df, color == "blue")

It works perfectly, but I would like to refer to color by string, something like this:

var <- "color"
filter(df, this_probably_should_be_a_function(var) == "blue").

I would be happy, to do this by any means and super-happy to make use of easy-to-read dplyr syntax.

1
  • 1
    For select and other methods you can use select_ to pass by variable, but I'm not sure how to do this with filter()...
    – Kevin
    Commented Jan 29, 2015 at 1:21

9 Answers 9

37

In the newer versions, 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

4
  • When typing (!!"term") I get Error in !"term" : invalid argument type. I am using dplyr 0.7.4. Commented Nov 5, 2017 at 0:34
  • 1
    @MichaelBarton I am using 0.7.3 and it is working with both the approaches in the Update. I am not sure what you meant by term, If you are passing a quoted string, then filter(df, (!!rlang::sym("color")) == "blue")
    – akrun
    Commented Nov 5, 2017 at 3:42
  • 1
    Yes you're right, this is my mistake. I must have gotten confused when typing this in, I shouldn't have put quotes around this. Commented Nov 5, 2017 at 17:59
  • 2
    Now !! has higher precedence and parentheses aren't needed anymore Commented Jul 1, 2019 at 0:13
27

For dplyr versions [0.3 - 0.7) (? - June 2017)

(For more recent dplyr versions, please see other answers to this question)

As of dplyr 0.3 every dplyr function using non standard evaluation (NSE, see release post and vignette) has a standard evaluation (SE) twin ending in an underscore. These can be used for passing variables. For filter it will be filter_. Using filter_ you may pass the logical condition as a string.

filter_(df, "color=='blue'")

#   color value
# 1  blue     1
# 2  blue     3
# 3  blue     4

Construing the string with the logical condition is of course straighforward

l <- paste(var, "==",  "'blue'")
filter_(df, l)
2
  • Using filter_ you may pass the logical condition as a string. Thank you for pointing this out. I really never understood how NSE worked in dplyr until I read that part of your post.
    – Berk U.
    Commented May 3, 2016 at 23:19
  • Broken link to the vignette, could you please update?
    – slhck
    Commented May 8, 2018 at 16:46
17

As of dplyr 0.7, some things have changed again.

library(dplyr)
df <- data.frame( 
  color = c("blue", "black", "blue", "blue", "black"), 
  value = 1:5)
filter(df, color == "blue")

# it was already possible to use a variable for the value
val <- 'blue'
filter(df, color == val)

# As of dplyr 0.7, new functions were introduced to simplify the situation
col_name <- quo(color) # captures the current environment
df %>% filter((!!col_name) == val)

# Remember to use enquo within a function
filter_col <- function(df, col_name, val){
  col_name <- enquo(col_name) # captures the environment in which the function was called
  df %>% filter((!!col_name) == val)
}
filter_col(df, color, 'blue')

More general cases are explained in the dplyr programming vignette.

3
  • 4
    Thanks. This was the answer I was looking for. This feels to me like a confusing direction for dplyr though. It took me a long time to parse and understand what quo and enquo are doing here. I can imagine I won't be the only one either, this feels like a very advanced piece of code almost like writing macros in a LISP. I like macros and LISPs but I don't know if they are to everyone's tastes, especially for writing relatively simple functions to manipulate tibbles. Commented Nov 5, 2017 at 0:48
  • @MichaelBarton These commands specify which environment to capture. I tried to add comments to clarify. A better explanation is in the programming vignette.
    – takje
    Commented Nov 6, 2017 at 9:32
  • 1
    Yes, this wasn't a comment on your answer, which is what I was looking for. Rather that this is a personal commentary on dplyr. I think it's difficult to ask users have to understand quo and enquo to write what I would consider even relatively simple functions using dplyr. Almost as if when teaching someone to write functions based on dplyr, you also have to bundle in an explanation about how to capture the environment with quo. Commented Nov 6, 2017 at 21:23
15

new with rlang version >= 0.4.0

.data is now recognized as a way to refer to the parent data frame, so reference by string works as follows:

var <- "color"
filter(df, .data[[var]] == "blue")

If the variable is already a symbol, then {{}} will dereference it properly

example 1:

var <- quo(color)
filter(df, {{var}} == "blue")

or more realistically

f <- function(v) {
    filter(df, {{v}} == "blue")
}
f(color) # Curly-curly provides automatic NSE support

More reading and examples are provided in the Programming with dplyr article/vignette.

2
  • The .data[[var]] approach here worked immediately for me to negate a filter in a pipeline (eg, like: df %>% filter(!.data[[var]] %in% df2[[var]])). I couldn't get some of the other solutions to work in this application right away.
    – steve_b
    Commented Jul 7, 2021 at 8:53
  • @steve_b these methods are solutions to different problems/for use in different cases. .data works when you have a string. {{ works when you have a symbol, e.g., an unquoted column name. Commented Sep 15, 2022 at 2:26
7

Often asked, but still no easy support afaik. However, with regards to this posting:

eval(substitute(filter(df, var == "blue"), 
                list(var = as.name(var))))
#   color value
# 1  blue     1
# 2  blue     3
# 3  blue     4
6

Several of the solutions above did not work for me. Now there is the as.symbol function, which we wrap in !!. Seems a bit simpler, sort of.

set.seed(123)

df <- data.frame( 
  color = c("blue", "black", "blue", "blue", "black"), 
  shape = c("round", "round", "square", "round", "square"),
  value = 1:5)

Now enter the variable as a string into the dplyr functions by passing it through as.symbol() and !!

var <- "color"
filter(df, !!as.symbol(var) == "blue")

#   color  shape value
# 1  blue  round     1
# 2  blue square     3
# 3  blue  round     4

var <- "shape"
df %>% group_by(!!as.symbol(var)) %>% summarise(m = mean(value))

#   shape      m
#   <fct>  <dbl>
# 1 round   2.33
# 2 square  4
1
  • Of all the answers here, this worked for me with dplyr 1.0.1, thanks!
    – Alex L
    Commented Sep 5, 2020 at 23:28
5

Here is one way to do it using the sym() function in the rlang package:

library(dplyr)

df <- data.frame( 
  main_color = c("blue", "black", "blue", "blue", "black"), 
  secondary_color = c("red", "green", "black", "black", "red"),
  value = 1:5, 
  stringsAsFactors=FALSE
)

filter_with_quoted_text <- function(column_string, value) {
    col_name <- rlang::sym(column_string)
    df1 <- df %>% 
      filter(UQ(col_name) == UQ(value))
    df1
}

filter_with_quoted_text("main_color", "blue")
filter_with_quoted_text("secondary_color", "red")
1
  • 1
    I ran into the double string use case. I don't understand why the normal filter(UQ(col_name) == UQ(value)) approach doesn't work, and one has to use rlang::sym(column_string) first. This case of double unquoting with == operator in filter() is not covered in any of the tutorials I found. Commented Jun 19, 2018 at 14:44
5

An update. The new dplyr1.0.0 has some fantastic new functionality that makes solving these sorts of problems far easier. You can read about it in the 'programming' vignette accompanying the new package.

Basically the .data[[foo]] function allows you to pass strings into functions more easily.

So you can do this

filtFunct <- function(d, var, crit) {
filter(d, .data[[var]] %in% crit)
}

filtFunct(df, "value", c(2,4))

#   color value
# 1 black     2
# 2  blue     4

filtFunct(df, "color", "blue")

#   color value
# 1  blue     1
# 2  blue     3
# 3  blue     4
3

This question was posted 6 years ago. dplyr is now up to version 1.0.2. Yet this is still a great discussion and helped me immensely with with my problem. I wanted to be able to construct filters from columns, operators, and values that are all specified by variables in memory. Oh, and for an indeterminate number of filters!

Consider the following list where I specify the column, the operator, and the value for two filters:

myFilters = 
  list(
    list(var = "color", op = "%in%", val = "blue"),
    list(var = "value", op = "<=", val = 3)
  )

From this list, I want to run:

dplyr::filter(color %in% "blue", value <= 3)

We can use lapply on the list above to create a list of call objects, force evaluation of the calls using the !!! operator, and pass that to filter:

library(dplyr)

df <- data.frame( 
  color = c("blue", "black", "blue", "blue", "black"), 
  value = 1:5)

result = 
  lapply(myFilters, function(x) call(x$op, as.name(x$var), x$val)) %>%
  {filter(df, !!!.)}

...and Shazam!

> result
  color value
1  blue     1
2  blue     3

That's a lot to absorb, so if it isn't immediately apparent what's happening, let me unpack it a bit. Consider:

var = "color"
op = "%in%"
val = "blue"

I'd want to be able to run:

filter(df, color %in% "blue")

and if I also have:

var2 = "value"
op2 = "<="
val2 = 3

I might want to be able to get:

filter(df, color %in% "blue", value <= 3)

The solution uses calls, which are unevaluated expressions. (See Hadley's Advanced R book) Basically, make a list of call object from variables, and then force evaluation of the calls using the !!! operator when calling dplyr::filter.

call1 = call(op, as.name(var), val)

Here is the value of call1:

> call1
color %in% "blue"

Let's create another call:

call2 = call(op2, as.name(var2), val2)

Put them in list:

calls = list(call1, call2)

and use !!! to evaluate the list of calls prior to sending them to filter:

result = filter(df, !!!calls)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.