Reputation: 3564
How can I avoid the trivial "a==a is always TRUE" condition in code where a data-variable and an env-variable share the same name, like:
library(dplyr)
cyl <- 8
## creates unintended results--doesn't actually filter anything out
fn_a <- function(data, cyl){
data %>%
filter(cyl==cyl) %>%
select(cyl)
}
mtcars %>% fn_a(cyl)
#> cyl
#> Mazda RX4 6
#> Mazda RX4 Wag 6
#> Datsun 710 4
#> Hornet 4 Drive 6
etc
changing the name of the env-variable (in this case the function argument) is obviously an option:
fn_b <- function(data, cyl_val){
data %>%
filter(cyl==cyl_val) %>%
select(cyl)
}
mtcars %>% fn_b(cyl)
#> cyl
#> Hornet Sportabout 8
#> Duster 360 8
#> Merc 450SE 8
#> Merc 450SL 8
#> Merc 450SLC 8
#> Cadillac Fleetwood 8
#> Lincoln Continental 8
#> Chrysler Imperial 8
#> Dodge Challenger 8
#> AMC Javelin 8
#> Camaro Z28 8
#> Pontiac Firebird 8
#> Ford Pantera L 8
#> Maserati Bora 8
but it's easier to remember function arguments without this renaming.
Is there a way to disambiguate between the env-variable and the data-variable with the same name?
Upvotes: 0
Views: 32