Domain Specific Quoting

This document discusses some of the hardest topics to understand in R. If you're an analyst you'll not need to worry too much about these topics, but for advanced R users it should be a thing to be aware of. The content is heavily influenced by Hadley Wickhams Advanced R Book and the tidyverse documentation.

Pretty Freakin' Weird

The following few lines of code will cause a common programmer to feel uneasy even though it is easy to imagine what it is supposed to do.

It's not so much what is happing, rather how it is happening. Even if you understand what %>% does you should notice something strange. The variables Time and Diet are not declared anywhere, yet we are able to use them. Within the context of the ChickWeight dataframe they are perfectly reasonable things to refer to but if feels a bit misterious. If I run Diet and Time outside of this group_by call I'd get an error.

In other languages and frameworks you would expect strings to be used as parameters or strings that are wrapped by a control mechanic (like sf.col("<str>") in spark). Here we are able to save some characters because apperantly R allows you to do things like this.

If you're used to python or C/C++ you should feel rather uneasy at this stage. The goal of this blogpost is to give more intuition in what is going on here both to myself and to anybody reading this.

API for Graphs

Let's make a small object that will learn a graph structure out of a dataframe. It will be a seperate R object. If you've never seen s3 classes before If you've never seen s3 classes before this blogpost or this resource might help. The graaf object will represent an bi-directional graph such that each relation between two people results in two directed arcs.

In this case the select verb will subset nodes and the grab verb will select relationships. It would be cool if we could pass in the name of the nodes or the types of edges without having to communicate strings.

This works! We see that it is useful to have this form of quoting such that it can communicate with dplyr (which is our datastructure).

The implementation of this is fine and all but it may still feel like this quoting stuff only acts as a sugar coat to evaluate variable names to strings. Let's consider an application in dplyr that is different.

Grouping

Let's make our own custom grouping function that just shows how often a certain subset occurs.

You may have noticed the triple !!!. This is the tidyverse way of telling dplyr that it can evaluate the quoted inputs of the function. The idea is that this pattern can replace the group_by_ pattern we used to have with strings.

Note that we are not merely passing variables in that need to be evaluated to strings. The group_by function can now actually evaluate what is passed in without any translation to strings.

At this point you probably appreciate quoting a bit more but probably still feel like all this quoting business is simply tied to dplyr or other things in the tidyverse. Is quoting just another way to commicate variables as if they are strings?

Another Reason to Quote

That's not the goal of all this quoting business. The goal is not to parse variables as if it were just a mere strings such that we can save on typing "". The idea is that we could make use of quoting to cause delayed evaluation. To demonstrate this, suppose that I have the following bit of code.

z <- x + y

There is nothing wrong with this expression, but it will give an error if there is no known x or y. So we could wrap it into an expression.

expr <- quo(z <- x + y)

This expression can be evaluated whenever we wish via the eval_tidy function from the rlang package. If we run it now, it will give an appropriate error.

This function outputs a function that will execute blocks of code whenever we call it. This will sort of work as a callback. Whenever it is called we can interpret it as an update mechanism receiving an event.

Every time that update() is called it will search for a dataframe to plot.

dataf <-data_frame(
x1 = rnorm(100),
x2 = rnorm(100))
update()

dataf <-data_frame(
x1 = rnorm(1000),
x2 = rnorm(1000))
update()

dataf <-data_frame(
x1 = rnorm(1000),
x2 = x1 + rnorm(1000))
update()

You may wonder in what edge case something like this may be useful. And it is fair to point out: when you're doing day to day analysis work you're probably not going to see an obvious oppotunity for delayed execution. Instead you're probably going to be using some tools like dplyr, ggplot2 and shiny to get on with you day to day work.

Conclusion

And to understand and appreciate the internals of those tools it helps to understand quoting. You don't need to understand everything of it to work with data but I find it enlightening (albeit a little bit confusing too).

The easiest way for me get my head to understand this material is to regard these quotes are mere expressions that are not evaluated yet, similar to how code in a function is also code that is not evaluated yet.

This is a post I wrote while teaching myself something new and I must admit that this quoting stuff does not immediately feel natural. So if this post feel indimidating: don't panic, just carry on. I'm glancing over some of the newer tidyverse stuff which is very very advanced and very very new. Odds are that 99% of the time, you'll not need to be mindful of any of this. A lot of things that quotes and expressions solve can also be solved via functions and proper programming too.

There are these naughty edge cases though when you may want things to be just this extra bit expressive and magic. Like how shiny is able to reactively update charts when something changes or how dplyr is able to parse the expression that is passed to a mutate function to cause a new column.

For the more edgy things you'd like to make I can imagine that this quoting business may be a step in a forward direction. I can also imagine that quoting will lead to better alternatives to functions like dplyr::summarise_ which did start feeling like a compromise. If you're used to other languages though, it is likely to be tricky to really get your head around this mechanic.