在 dplyr::filter 中传递一个字符串作为变量名 [英] Pass a string as variable name in dplyr::filter
问题描述
我使用 mtcars 数据集来说明我的问题.
I'm using mtcars dataset to illustrate my question.
例如,我想将数据子集到 4 缸汽车.我可以这样做:
For example, I want to subset data to 4-cyl cars.I can do:
mtcars %>% filter(cyl == 4)
在我的工作中,我需要传递一个字符串变量作为我的列名.例如:
In my work, I need to pass a string variable as my column name. For example:
var <- 'cyl'
mtcars %>% filter(var == 4)
我也做过:
mtcars %>% filter(!!var == 4)
在这两种情况下,我的数据框都是空的.
In both cases, I got empty dataframe.
推荐答案
!!
或 UQ
对变量求值,所以 mtcars %>% filter(!!var == 4)
与 mtcars %>% filter('cyl' == 4)
相同,其中条件总是评估为假;您可以通过在过滤器函数中打印 !!var
来证明这一点:
!!
or UQ
evaluates the variable, so mtcars %>% filter(!!var == 4)
is the same as mtcars %>% filter('cyl' == 4)
where the condition always evaluates to false; You can prove this by printing !!var
in the filter function:
mtcars %>% filter({ print(!!var); (!!var) == 4 })
# [1] "cyl"
# [1] mpg cyl disp hp drat wt qsec vs am gear carb
# <0 rows> (or 0-length row.names)
要将var
计算为cyl
列,您需要先将var
转换为cyl
的符号,然后将符号 cyl
计算为一列:
To evaluate var
to the cyl
column, you need to convert var
to a symbol of cyl
first, then evaluate the symbol cyl
to a column:
使用rlang
:
library(rlang)
var <- 'cyl'
mtcars %>% filter((!!sym(var)) == 4)
# mpg cyl disp hp drat wt qsec vs am gear carb
#1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
#2 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
#3 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
# ...
或者使用 baseR 中的 as.symbol/as.name
:
Or use as.symbol/as.name
from baseR:
mtcars %>% filter((!!as.symbol(var)) == 4)
mtcars %>% filter((!!as.name(var)) == 4)
这篇关于在 dplyr::filter 中传递一个字符串作为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!