Search code examples
rggplot2magrittr

What does the magrittr dot/period (".") operator do when it's at the very beginning of a pipeline?


I don't understand what the . in the following code is doing or where to find documentation for it:

library(tidyverse)

ggplot(iris) + 
  geom_point(
    aes(x=Sepal.Length, y=Sepal.Width), 
    data = . %>% filter(Species == 'setosa')
  )

This appears to be behaving quite differently from the usage described in What does the dplyr period character "." reference? where the . does not appear in the left-hand-most position.

The docs here say merely

A pipeline with a dot (.) as LHS will create a unary function. This is used to define the aggregator function.

but this is not at all clear to me and I'm hoping for more information.


Solution

  • The confusion here can actually come from two places.

    First, yes, the . %>% something() syntax creates a "unary" function that takes one argument. So:

    . %>% filter(Species == 'setosa')
    

    is equivalent to

    function(.) filter(., Species == 'setosa')
    

    The second part here is that ggplot2 layers can actually take a function as their data argument. From e.g. ?geom_point:

    The data to be displayed in this layer. There are three options:

    ...

    A function will be called with a single argument, the plot data. The return value must be a data.frame, and will be used as the layer data.

    So the function that is passed to geom_point will always be applied to the default plot data (i.e. the data defined in ggplot()).

    Note that your linked question concerns the use of . in funs(), which is not directly related to it's use here.