1

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
jzadra
  • 4,012
  • 2
  • 26
  • 46

1 Answers1

3

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)}
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks. I'm curious, then, why data.frame(x = 1:10, y = 11:20) %>% .$y doesn't give something like data.frame(dd, dd$y). Also, doesn't my first example contain a "lone dot placed somewhere else in the call"? – jzadra Jul 19 '17 at 20:52
  • Because `.$y` is equivalent to `'$'(., y)` which is already putting the data.frame where you want it. You could also use `%>% '$'(y)` without the dot. It's really more about not going into nested calls than a "lone dot" so I was being a bit imprecise there. – MrFlick Jul 19 '17 at 20:58
  • 1
    @jzadra Btw, there's some esoterics associated with how magrittr behaves when `.` appears explicitly as an argument to the function. Namely, if it is a freestanding argument to the function (as MrFlick showed is the case in your example), then the dot is not additionally given as the first argument. So, for example `"A" %>% setNames(.)` is not equivalent to `setNames("A", "A")` and in fact fails. https://github.com/tidyverse/magrittr/issues/128 (Oh, just noticed MrFlick edited the comment to cover that. Anywho, I'll leave this comment here.) – Frank Jul 19 '17 at 21:04
  • For this exampe, you may want to use : `data.frame(x = 1:10, y = 11:20) %$% min(y)` – moodymudskipper Aug 15 '17 at 15:51