如何在dplyr 0.7.0中将列名指定为字符元素?

时间:2017-08-01 17:07:17

标签: r dplyr

借鉴another question's answer

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

典型的示例采用......

的形式
# 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')

...但是如果你想要一个字符串指定的颜色列的名称呢?

E.g。

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

或者调用带有filter_col(df, "color", "blue")

等签名的函数

1 个答案:

答案 0 :(得分:4)

按照aosmith的链接将我们带到了lukeA的答案......对于这个用例进行了修改:

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')

关键部分是rlang::sym()生成一个可以通过unquo运算符!!展开的对象。虽然这个问题的答案是another question的重复,但我现在要离开它,因为我相信这在问题如何指定方面有点重要/没有太多正确的答案这个问题。 :)