如何在dplyr :: filter中使用变量? [英] How to use a variable in dplyr::filter?

查看:251
本文介绍了如何在dplyr :: filter中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数据框中的列名称相同的变量:

I have a variable with the same name as a column in a dataframe:

df <- data.frame(a=c(1,2,3), b=c(4,5,6))
b <- 5

我想得到 df $ b == b 的行,但是dplyr将其解释为 df $ b == df $ b

I want to get the rows where df$b == b, but dplyr interprets this as df$b == df$b:

df %>% filter(b == b) # interpreted as df$b == df$b
#   a b
# 1 1 4
# 2 2 5
# 3 3 6

如果我更改变量名称,它的工作原理是:

If I change the variable name, it works:

B <- 5
df %>% filter(b == B) # interpreted as df$b == B
#   a b
# 1 2 5

我想知道有没有更好的方法来告诉过滤器 b 是指外部变量。

I'm wondering if there is a better way to tell filter that b refers to an outside variable.

推荐答案

使用 get 函数从环境中获取变量的值。

You could use the get function to fetch the value of the variable from the environment.

df %>% filter(b == get("b")) # Note the "" around b

这篇关于如何在dplyr :: filter中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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