使用与列名同名的全局变量过滤数据框 [英] Filter dataframe using global variable with the same name as column name

查看:75
本文介绍了使用与列名同名的全局变量过滤数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

library(dplyr)

玩具数据集:

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

工作正常:

df %>% filter(y == 5)
  x y
1 2 5

这也可以:

z <- 5
df %>% filter(y == z)
  x y
1 2 5

但这失败

y <- 5
df %>% filter(y == y)
  x y
1 1 4
2 2 5
3 3 6

显然,dplyr不能区分其 y列和全局变量 y
是否可以告诉dplyr第二个y是全局变量?

Apparently, dplyr cannot make the distinction between its column y and the global variable y. Is there a way to tell dplyr that the second y is the global variable?

推荐答案

您可以这样做:

df %>% filter(y == .GlobalEnv$y)

或:

df %>% filter(y == .GlobalEnv[["y"]])

or:

两者都在这种情况下起作用,但是如果所有这些都在函数内部进行则不会。但是 get 将:

both of which work in this context, but won't if all this is going on inside a function. But get will:

df %>% filter(y == get("y"))
f = function(df, y){df %>% filter(y==get("y"))}

所以请使用 get

或仅使用 df [df $ y == y,] 代替 dplyr

这篇关于使用与列名同名的全局变量过滤数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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