Use pipe without feeding first argument

后端 未结 1 1135
星月不相逢
星月不相逢 2020-12-09 17:40

Is the %>% pipe operator always feeding the left-hand side (LHS) to the first argument of the right-hand side (RHS)? Even if the first argument is specified

相关标签:
1条回答
  • 2020-12-09 18:26

    Is the %>% pipe operator always feeding the left-hand side (LHS) to the first argument of the right-hand side (RHS)? Even if the first argument is specified again in the RHS call?

    No. You’ve noticed the exception yourself: if the right-hand side uses ., the first argument of the left-hand side is not fed in. You need to pass it manually.

    However, this is not happening in your case because you’re not using . by itself, you’re using it inside an expression. To avoid the left-hand side being fed as the first argument, you additionally need to use braces:

    iris %>% {cor(x = .$Sepal.Length, y = .$Sepal.Width)}
    

    Or:

    iris %$% cor(x = Sepal.Length, y = Sepal.Width)
    

    — after all, that’s what %$% is there for, as opposed to %>%.

    But compare:

    iris %>% lm(Sepal.Width ~ Sepal.Length, data = .)
    

    Here, we’re passing the left-hand side expression explicitly as the data argument to lm. By doing so, we prevent it being passed as the first argument to lm.

    0 讨论(0)
提交回复
热议问题