Referencing variables in functions using {{}}

Hello all,

I was trying to write a function to streamline my 'tabyl' function calls using the following syntax:

tab_freq <- function(data, v1, v2) {
data %>%
tabyl(v1, v2) %>%
adorn_totals(c("row", "col")) %>%
adorn_percentages("all") %>%
adorn_pct_formatting(2) %>%
adorn_ns()
}

tab_freq(df, var1, var2)

But I kept on getting the error: Error in .f(.x[[i]], ...) : object 'var1' not found

I then found a solution on the RStudio thread here: Problem for loop with Janitor and Rlang

It used curly braces to reference the variables v1 and v2 within the function:

tab_freq <- function(data, v1, v2) {
data %>%
tabyl({{ v1 }}, {{ v2 }}) %>%
adorn_totals(c("row", "col")) %>%
adorn_percentages("all") %>%
adorn_pct_formatting(2) %>%
adorn_ns() # no need to print here
}

I was definitely happy to find the solution. However, I have found no references or documentation for this {{}} convention anywhere on the web. Could someone please refer me to any documentation on referencing variables in this way? So far the attached web link is the only place I've seen this.

Thank you in advance!

RJ

Start with

https://www.njtierney.com/post/2019/07/06/jq-bare-vars/

or 7.5.2 here

1 Like

You can see the blog post where this new syntax was announced

This blog post also
https://www.brodrigues.co/blog/2019-06-20-tidy_eval_saga/

This one

And I am sure this will be explained here at some point

1 Like

Do we have an equivalent for !!! like {{{ }}} ?

regards,

Not yet no. But {{x}} is kind of equivalent to !!enquo(x). What would you like to do with !!! ?
Using !!! is pretty simple already...

Just asking as I have seen this:

By the way, what do you mean by: " Using !!! is pretty simple already..." ?

Yes you are right, there could be a {{{ }}} but I think !!! enquos is less frequent.

About simple, I had this kind of splicing in mind (dummy example)

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

# splice list
new_col <- list(
  a = TRUE,
  b = FALSE,
  c = NA
)

tibble(A = rnorm(10)) %>%
  mutate(!!!new_col)
#> # A tibble: 10 x 4
#>         A a     b     c    
#>     <dbl> <lgl> <lgl> <lgl>
#>  1 -1.09  TRUE  FALSE NA   
#>  2  1.19  TRUE  FALSE NA   
#>  3  0.206 TRUE  FALSE NA   
#>  4  0.632 TRUE  FALSE NA   
#>  5 -0.711 TRUE  FALSE NA   
#>  6  1.74  TRUE  FALSE NA   
#>  7  0.779 TRUE  FALSE NA   
#>  8  1.21  TRUE  FALSE NA   
#>  9  0.583 TRUE  FALSE NA   
#> 10 -0.709 TRUE  FALSE NA

Created on 2019-11-02 by the reprex package (v0.3.0)

But I guess it depends on the situation and the example. Forget I said that word simple :sweat_smile:

Thank you very much indeed @cderv.
:slightly_smiling_face: For me tidy evaluation subject is never simple,

best regards,
Andrzej

1 Like