问题描述
我想在 dplyr
的函数中使用变量名作为字符串.请看下面的例子:
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")
它工作得很好,但我想通过字符串来引用color
,就像这样:
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").
我很乐意以任何方式做到这一点,并且非常乐意使用易于阅读的 dplyr
语法.
I would be happy, to do this by any means and super-happy to make use of easy-to-read dplyr
syntax.
推荐答案
在较新的版本中,我们可以使用我们可以创建引用的变量然后取消引用(UQ
或 !!
) 用于评估
In the newer versions, we can use 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")
应该有效(正如@Moody_Mudskipper 评论的那样)
should work (as @Moody_Mudskipper commented)
我们也可以使用:
filter(df, get(var, envir=as.environment(df))=="blue")
#color value
#1 blue 1
#2 blue 3
#3 blue 4
重新排列解决方案的顺序
Rearranged the order of solutions
这篇关于在 dplyr 的函数中使用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!