Could someone explain why f1 behaves differently than f2 in this example:
library(dplyr)
f1 <- function(data, year){
data %>%
filter(year == year)
}
f2 <- function(data, y){
data %>%
filter(year == y)
}
f3 <- function(data, year){
data %>%
filter(!!year == year)
}
df <- data.frame(year = 2000:2005)
f1(df, 2005)
#> year
#> 1 2000
#> 2 2001
#> 3 2002
#> 4 2003
#> 5 2004
#> 6 2005
f2(df, 2005)
#> year
#> 1 2005
f3(df, 2005)
#> year
#> 1 2005
I know this has something to do with tidy evaluation and I had a look at the vignette on Programming with dplyr. But the example here seems somewhat different.
I see that the problem can be fixed by using !! in f3, but I am not entirely sure what happens here. I would be interested to know if this is the optimal solution to the problem and if it is recommended to always use !! in similar situations.