如何在dplyr 0.7.0中将列名称指定为字符元素? [英] How can you specify a column name as character element in dplyr 0.7.0?
问题描述
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?
例如
column_name <- "color"
col_name <- quo(column_name) # <- something else goes here
df %>% filter((!!col_name) == "blue")
或调用签名为 filter_col(df, color, blue)
的函数?
推荐答案
按照aosmith的链接,我们可以找到lukeA的答案...对此用例进行了修改:
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')
关键部分是 rlang :: sym()
产生的对象可以被expa由非定元运算符 !!
找到。尽管此问题的答案是另一个问题的重复a>我将暂时搁置它,因为我认为这对问题的指定方式更为重要/对这个问题不能有太多正确的答案。 :)
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. :)
这篇关于如何在dplyr 0.7.0中将列名称指定为字符元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!