dplyr函数如何区分具有相同名称的列和变量? [英] how can dplyr functions discriminate columns and variables with the same name?

查看:84
本文介绍了dplyr函数如何区分具有相同名称的列和变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我不小心创建了一个与 data.frame 中的列具有相同名称的变量,之后使用 dplyr 函数。该名称通常被视为列名称而不是变量名称。请参阅以下示例:

Sometimes I accidently create a variable that has the same name with a column in a data.frame and later use the variable in dplyr functions. the name is often treated as column name not variable name. See the follow example:

library(dplyr)

packageVersion("dplyr")
#> [1] '0.6.0'
mtcars %>% filter(mpg == 21)
#>   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1  21   6  160 110  3.9 2.620 16.46  0  1    4    4
#> 2  21   6  160 110  3.9 2.875 17.02  0  1    4    4
mpg.val <- 21
mtcars %>% filter(mpg == mpg.val)
#>   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1  21   6  160 110  3.9 2.620 16.46  0  1    4    4
#> 2  21   6  160 110  3.9 2.875 17.02  0  1    4    4
mpg <- 21
mtcars %>% filter(mpg == mpg)
#>     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> ...

在第三种情况下,如何告诉过滤器第二个 mpg 是一个变量名称,不是列名,得到的结果是前两种情况? (另外我使用dplyr 0.6.0。)

In the third case, how to tell filter that the second mpg is a variable name not a column name and get the results as the first two cases? (In addition I am using dplyr 0.6.0.)

get reprex 生成的结果:

mpg <- 21
mtcars %>% filter(mpg == get("mpg"))
#>     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> ...

添加环境工程:

mtcars %>% filter(mpg == get("mpg", .GlobalEnv))
#  mpg cyl disp  hp drat    wt  qsec vs am gear carb
#1  21   6  160 110  3.9 2.620 16.46  0  1    4    4
#2  21   6  160 110  3.9 2.875 17.02  0  1    4    4


推荐答案

我们可以使用 .GlobalEnv

mtcars %>%
     filter(mpg == .GlobalEnv$mpg)
#   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#1  21   6  160 110  3.9 2.620 16.46  0  1    4    4
#2  21   6  160 110  3.9 2.875 17.02  0  1    4    4

这篇关于dplyr函数如何区分具有相同名称的列和变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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