3

I'm performing an academic exercise that demonstrates an issue with my understanding of dplyr. Let me reconstruct the iris data set using base-R syntax:

library(dplyr)

bind_cols(iris[1], iris[-1])

OK, great that works. Now, I'll pipe everything with dplyr - and - it doubles every column in the iris data set. Shouldn't these two pieces of code produce identical results?

iris %>% bind_cols(.[1], .[-1])
alistaire
  • 42,459
  • 4
  • 77
  • 117
stackinator
  • 5,429
  • 8
  • 43
  • 84
  • 6
    If you do anything to `.` like subset it, it will still be passed as the first parameter, like the second example above. If you pass `.` unaltered to a parameter, it will only be passed to that parameter, e.g. `100 %>% rnorm(10, mean = .)`. If you want to keep it from being passed to the first parameter, wrap the expression in braces, e.g. `iris %>% {bind_cols(.[1], .[-1])}` and it will only be passed where specified by `.`. – alistaire Dec 30 '17 at 23:21
  • That explains it. Thank you. – stackinator Dec 30 '17 at 23:42

1 Answers1

4

Please see the following. iris %>% bind_cols(.[1], .[-1]) is the same as bind_cols(iris, iris[1], iris[-1]) because the first argument of bind_cols is the one before %>%. So the result makes sense to me.

aa <- iris %>% bind_cols(.[1], .[-1])

bb <- bind_cols(iris, iris[1], iris[-1])

identical(aa, bb)
# [1] TRUE
www
  • 38,575
  • 12
  • 48
  • 84
  • 4
    Nice. And `iris %>% {bind_cols(.[1], .[-1])}` would produce same as `bind_cols(iris[1], iris[-1])`. – Tino Dec 30 '17 at 23:13
  • @Tino Thanks for sharing. I did not know the use of `{` before. – www Dec 30 '17 at 23:17
  • 3
    I find it useful when I want to plot something but also print a table based on same data: `df %T>% {print(ggplot() + ...)} %>% ...`, where `%T>%` is that fancy kind of pipe-split from `magrittr`. – Tino Dec 30 '17 at 23:26