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

和自甴很熟 提交于 2019-12-10 16:44:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/53436488/what-does-the-magrittr-dot-period-operator-do-when-its-at-the-very-beginn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!