0

Borrowing from another question's answer:

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

The typically presented example takes the form of ...

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

# Remember to use enquo within a function
filter_col <- function(df, col_name, val){
  col_name <- enquo(col_name)
  df %>% filter((!!col_name) == val)
}
filter_col(df, color, 'blue')

... but what if you wanted to have the name of the color column specified by a string?

E.g.

column_name <- "color"
col_name <- quo(column_name) # <- something else goes here
df %>% filter((!!col_name) == "blue")

Or call a function with a signature like, filter_col(df, "color", "blue")?

eddi
  • 49,088
  • 6
  • 104
  • 155
russellpierce
  • 4,583
  • 2
  • 32
  • 44
  • 1
    You need `sym` from *rlang* for variables as strings. See, e.g., [here](https://stackoverflow.com/questions/44121728/programming-with-dplyr-using-string-as-input/44122936#44122936) – aosmith Aug 01 '17 at 22:46

1 Answers1

4

Following aosmith's link takes us to lukeA's answer... which modified for this use case is:

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

# In interactive mode
column_name <- rlang::sym("color")
df %>% filter((!!column_name) == "blue")

# In a function
filter_col <- function(df, col_name_as_string, val){
  col_name <- rlang::sym(col_name_as_string)
  df %>% filter((!!col_name) == val)
}
filter_col(df, 'color', 'blue')

The key part is that rlang::sym() produces an object that can be expanded by the unquo operator !!. Although the answer to this question is a duplicate of another question I'm going to leave it for now because I believe this is a bit more on point in how the question is specified / there can't be too many right answers to this problem. :)

russellpierce
  • 4,583
  • 2
  • 32
  • 44