More on Macros in R

February 23, 2019

(This article was first published on R – Win-Vector Blog, and kindly contributed to R-bloggers)

Recently ran into something interesting in the R macros/quasi-quotation/substitution/syntax front:


Romain François: “[email protected]_lionelhenry reveals planned double curly syntax At #satRdayParis as a possible replacement, addition to !! and enquo()”

It appears !! is no longer the last word in substitution (it certainly wasn’t the first).

The described effect is actually already pretty easy to achieve in R.


group_by <- wrapr::bquote_function(group_by)
summarize <- wrapr::bquote_function(summarize)

my_average <- function(data, grp_var, avg_var) {
  data %>%
    group_by(.( grp_var )) %>%
    summarize(avg = mean(.( avg_var ), na.rm = TRUE))

data <- data.frame(x = 1:10, g = rep(c(0,1), 5))


## # A tibble: 2 x 2
##       g   avg
## 1     0     5
## 2     1     6

Or if you don’t want to perform the quoting by hand.

my_average <- function(data, grp_var, avg_var,
                       grp_var_name = substitute(grp_var),
                       avg_var_name = substitute(avg_var)
                       ) {
  data %>%
    group_by(.( grp_var_name )) %>%
    summarize(avg = mean(.( avg_var_name ), na.rm = TRUE))

my_average(data, g, x)

## # A tibble: 2 x 2
##       g   avg
## 1     0     5
## 2     1     6

And we can use the same Thomas Lumley / bquote() notation for string interpolation.

group_var <-"g")
avg_var <-"x")

wrapr::sinterp("group_var was .(group_var), and avg_var was .(avg_var)")

# [1] "group_var was g, and avg_var was x"

The .() notation has a great history in R and has been used by data.table for years.

To leave a comment for the author, please follow the link and comment on their blog: R – Win-Vector Blog. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)