3

I'm sorry if this is a repeat but I can't find it:

I'm trying to use the . placeholder with the pipe (%>%) from magrittr, and it seems not to work when it's the second call.

For instance, this works:

data.frame(t = c(1.1,2.2,3.3), y = c(1,2,3)) %$% (t-y)^2 %>% sum(.)

But this doesn't:

data.frame(t = c(1.1,2.2,3.3), y = c(1,2,3)) %$% (t-y)^2 %>% sum(.)/length(.) 

Any intuition for why this is happening? Thanks!

Danny

Danny
  • 383
  • 2
  • 3
  • 16
  • Not a dupe, but I asked a similar question about a month ago and got some good explanations there: https://stackoverflow.com/q/50729045/5325862 – camille Jul 17 '18 at 12:49

1 Answers1

2

We need to place it inside the braces for evaluating as a unit

data.frame(t = c(1.1,2.2,3.3), y = c(1,2,3)) %$%
          (t-y)^2 %>% 
          {sum(.)/length(.)} 
#[1] 0.04666667

which is the same as mean

data.frame(t = c(1.1,2.2,3.3), y = c(1,2,3)) %$%
      (t-y)^2 %>% 
      mean
#[1] 0.04666667
akrun
  • 874,273
  • 37
  • 540
  • 662