4

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
#> ...

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 results generated by 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
#> ...

Add environment works:

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
mt1022
  • 16,834
  • 5
  • 48
  • 71
  • Possible duplicate of [Non-standard evaluation (NSE) in dplyr's filter\_ & pulling data from MySQL](https://stackoverflow.com/questions/26492280/non-standard-evaluation-nse-in-dplyrs-filter-pulling-data-from-mysql) – Adam Quek Jun 01 '17 at 07:29
  • @AdamQuek, How does the linked question solve my problem? Could you explain a little bit? – mt1022 Jun 01 '17 at 07:36
  • @mt1022 `mtcars %>% filter(mpg == get("mpg"))` works for me. `dplyr 0.5.0` – Ronak Shah Jun 01 '17 at 07:37
  • @RonakShah, I have to use `get("mpg", .GlobalEnv)` to make it work. – mt1022 Jun 01 '17 at 07:40

1 Answers1

1

We can use .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
akrun
  • 874,273
  • 37
  • 540
  • 662