0

I asked a question about accessing variable in global environment with the same name as one of the column name in dplyr functions. One solution I received was using get. However, new matter arises. Without specify environment explicitly, the result is different (see the following), Could someone explain why?

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

# dplyr 0.5.0
mtcars %>% filter(mpg == get("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
Henrik
  • 65,555
  • 14
  • 143
  • 159
mt1022
  • 16,834
  • 5
  • 48
  • 71
  • 2
    I assume it's a side effect of the major changes from 0.5 to 0.6 in terms of standard evaluation / non-standard evaluation approaches – talat Jun 01 '17 at 08:18
  • I think the new behavior makes sense, while the old one was a bug. `get`, by default, should look in the current environment rather in the parent, hence the current behavior is the correct one which makes your question kind of obsolete IMO. – David Arenburg Jun 01 '17 at 08:53
  • Agreed. Also "Explicit is better than implicit". – mt1022 Jun 01 '17 at 10:56

0 Answers0