简体   繁体   中英

How can you specify a column name as character element in dplyr 0.7.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?

Eg

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") ?

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM