如何在 dplyr::filter 中使用变量? [英] How to use a variable in dplyr::filter?
本文介绍了如何在 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
我想知道是否有更好的方法来告诉 filter
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屋!
查看全文