问题描述
我想在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函数中使用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!