package "dplyr" has a chain operator. But I have a problem with how to get the right side term itself.
For example:
c(5,7,8,1) %>% sum(`[`(1:3)) # get result 27 (This is wrong)
c(5,7,8,1) %>% sum(.[1:3]) # get result 41 (This is also wrong)
c(5,7,8,1) %>% `[`(1:3) %>% sum() # get result 20 (This is right)
Why the first line and second line codes are wrong? What has happened in them?
%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).
What is the Pipe Operator? The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.
The dot .
is correct. However, %>%
also inserts it as the first argument:
x = c(5,7,8,1)
x %>% sum(.[1 : 3])
Is the same as:
sum(x, x[1 : 3])
You can explicitly prevent this behaviour by wrapping the expression in braces:
x %>% {sum(.[1 : 3])}
However, at this point it may be better to split the pipeline up a bit more (as you’ve done yourself):
x %>% `[`(1 : 3) %>% sum()
Or, using magrittr helper functions (requires library(magrittr)
):
x %>% extract(1 : 3) %>% sum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With