Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the "dplyr" chain operator %>% get the left side itself in R? [duplicate]

Tags:

r

dplyr

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?

like image 871
xirururu Avatar asked Oct 30 '15 10:10

xirururu


People also ask

What does %>% mean in Dplyr?

%>% 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 function in R?

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.


1 Answers

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()
like image 143
Konrad Rudolph Avatar answered Sep 28 '22 12:09

Konrad Rudolph