Use curly curly notation in a function that gets called by another function

Dear All,
I wrote a function f01 using the new curly curly notation. Everything works fine.
If I know call this function from inside another function f02 the code fails, most probably because
f02 tries to evaluate select_this and not simply hands it over to f01 (this is what I would like it to do).
Thanks a lot for input!

mtcars %>% 
  select(mpg)

f01 <- function(df, select_this) {
  df %>% 
    select({{select_this}})
}

f01(mtcars, mpg)

f02 <- function(df, select_this) {
  f01(df, select_this)
}

f02(mtcars, mpg)

Roughly: once your code depends on that sort of quoting/unquoting you have to place it (and document it) many more places (such as in f02). The following works:

library("dplyr")
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

mtcars %>% 
  select(mpg)
#>                      mpg
#> Mazda RX4           21.0
#> Mazda RX4 Wag       21.0
#> ...

f01 <- function(df, select_this) {
  df %>% 
    select({{select_this}})
}

f01(mtcars, mpg)
#>                      mpg
#> Mazda RX4           21.0
#> Mazda RX4 Wag       21.0
#> ...

f02 <- function(df, select_this) {
  f01(df, {{select_this}})
}

f02(mtcars, mpg)
#>                      mpg
#> Mazda RX4           21.0
#> Mazda RX4 Wag       21.0
#> ...

Honestly I think it is a bit of an argument against the technique and for using explicit lists of columns instead.

2 Likes

Great! Thanks a lot for this simple solution!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.