Search code examples
rmagrittr

Accessing components of data from the "." (dot) operator with magrittr


I'm not clear on how to apply functions to components of data using the dot (".") with magrittr such as columns of a data from or items in a list.

Example:

> data.frame(x = 1:10, y = 11:20) %>% .$y
[1] 11 12 13 14 15 16 17 18 19 20

It seems that accessing the data should work the same as applying a function to it, but it does not:

> data.frame(x = 1:10, y = 11:20) %>% min(.$y)
[1] 1

Solution

  • The data.frame will be passed as the first parameter unless a lone dot is placed somewhere else in the call.

    data.frame(x = 1:10, y = 11:20) %>% min(.$y)
    

    is the same as

    dd <- data.frame(x = 1:10, y = 11:20)
    min(dd, dd$y)
    # [1] 1
    

    This is by design.

    You would have to use a code block

    data.frame(x = 1:10, y = 11:20) %>% {min(.$y)}