问题
For whatever reason I was playing with magrittr
pipe syntax, and came across a weird error that occurs when you scope explicitly qualify the call to %>%
. I know that using the syntax below destroys the purpose of the pipe, but I'm curious as to why the error occurs.
The first call to sum
works as expected and outputs a 1
.
The second call causes the error: Error in pipes[[i]] : subscript out of bounds
.
library(magrittr)
`%>%`(1,sum())
magrittr::`%>%`(1,sum())
Looking at the pipe's source code I'm thinking the cause for the error is related to the first lines manipulating the environment, but I'm sure as to what problem it's introducing.
function (lhs, rhs) {
parent <- parent.frame()
env <- new.env(parent = parent)
chain_parts <- split_chain(match.call(), env = env)
Can anyone explain this behavior?
回答1:
The pipe arguments (%>%, %$%, etc...) are all actually the same pipe()
function in magrittr. One of the first things that function does is to split the call into its constituent parts using an internal, non-exported function split_chain
.
split_chain()
takes the first element of the call (the function used, in this case, one of the pipe operators) and runs it through another internal, non-exported function called is_pipe()
which looks like:
function(pipe)
{
identical(pipe, quote(`%>%`)) ||
identical(pipe, quote(`%T>%`)) ||
identical(pipe, quote(`%<>%`)) ||
identical(pipe, quote(`%$%`))
}
if this doesn't come back as true, the function exits returning a list that is missing the pipe type and the right-handed side of the argument which causes problems. When scoping, a la magrittr::'%>%'
the first part of the call includes the explicit scoping and so it fails these hard coded checks.
来源:https://stackoverflow.com/questions/43786599/error-in-magrittr-pipe-when-using-magrittr