How do you end a pipe with an assignment operator?

It looks like you're trying to decorate the %>% pipeline operator with the side-effect of creating a new object. One would assume that you could use the assignment operator -> for this, but it won't work in a pipeline. This is because -> has lower precedence than user-defined operators like %>%, which messes up the parsing: your pipeline will be parsed as (initial_stages) -> (final_stages) which is nonsensical.

A solution is to replace -> with a user-defined version. While we're at it, we might as well use the lazyeval package, to ensure it will create the object where it's supposed to go:

`%->%` <- function(value, x)
{
    x <- lazyeval::lazy(x)
    assign(deparse(x$expr), value, x$env)
    value
}

An example of this in use:

smry <- mtcars %>% 
    group_by(cyl) %->%   # ->, not >
    tmp %>%
    summarise(m=mean(mpg))

tmp
#Source: local data frame [32 x 11]
#Groups: cyl
#
#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#..  ... ...   ... ...  ...   ...   ... .. ..  ...  ...

smry
#Source: local data frame [3 x 2]
#
#  cyl        m
#1   4 26.66364
#2   6 19.74286
#3   8 15.10000

It's probably easiest to do the assignment as the first thing (like scoa mentions) but if you really want to put it at the end you could use assign

mtcars %>% 
  group_by(cyl) %>% 
  summarize(m = mean(hp)) %>% 
  assign("bar", .)

which will store the output into "bar"

Alternatively you could just use the -> operator. You mention it in your question but it looks like you use something like

mtcars %>% -> yourvariable

instead of

mtcars -> yourvariable

You don't want to have %>% in front of the ->

Tags:

R

Dplyr

Magrittr