在dplyr :: filter中将字符串作为变量名传递 [英] Pass a string as variable name in dplyr::filter

查看:110
本文介绍了在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),条件始终为false;您可以通过在过滤器函数中打印 !! 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
# ...

或使用 as.symbol / as.name

mtcars %>% filter((!!as.symbol(var)) == 4)

mtcars %>% filter((!!as.name(var)) == 4)

这篇关于在dplyr :: filter中将字符串作为变量名传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆