dplyr,使用具有非标准评估的过滤器 [英] dplyr, use filter with non-standard evaluation

查看:66
本文介绍了dplyr,使用具有非标准评估的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用动态变量名称为 dplyr filter()函数:

I would like to use the filter() function from dplyr with a dynamic variable name :

data(mtcars)
var1 <- 'hp'

mtcars %>% filter(hp == 110)      # works
mtcars %>% filter(var1 == 110)    # doesn't works

使用新版本的dplyr程序包,似乎可以执行此操作(不使用lazyeval程序包),但是我没有做到这一点..会有所帮助。

With new version of dplyr package, it seems to be possible to do this (without using the lazyeval package), but I don't manage to do it .. Some helps will be appreciated.

测试失败:

mtcars %>% filter(!!var1 == 110)
mtcars %>% filter(!!!var1 == 110)
mtcars %>% filter((!!var1) == 110)
mtcars %>% filter(quo(var1) == 110)
mtcars %>% filter(~var1 == 110)
mtcars %>% filter(quo(~var1) == 110)
var2 <- enquo(var1)

使用 select() mutate()<的成功测试/ em>:

Successfull tests with select() and mutate():

mtcars %>% select(!!!var1) %>% head()      # works


推荐答案

这看起来很尴尬解决方案仅使用dplyr软件包,并且您可以在字符输入中使用SE替代项(以_结尾)。 (请参见小插图( nse)。)

This is one awkward looking solution using only the dplyr package and the fact that you can use SE alternatives (ending with _) with a character input. (See vignette("nse").)

library(dplyr) 
data(mtcars)
var1 <- "hp"
mtcars %>% filter_(paste(var1, "== 110"))

这篇关于dplyr,使用具有非标准评估的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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