16

I want to end a pipe with an assignment operator in R.

my goal (in pseudo R):

data %>% analysis functions %>% analyzedData

where data and analyzedData are both a data.frame.

I've tried a few variants of this, each giving a unique error message. some iterations I've tried:

data %>% analysis functions %>% -> analyzedData
data %>% analysis functions %>% .-> analyzedData
data %>% analysis functions %>% <-. analyzedData
data %>% analysis functions %>% <- analyzedData

Error messages:

Error in function_list[[k]](value) : 
  could not find function "analyzedData"
Error: object 'analyzedData' not found
Error: unexpected assignment in: ..

Update: the way I figured out to do this is:

data %>% do analysis %>% {.} -> analyzedData

This way, to troubleshoot / debug a long pipe, you can drop these two line into your pipe to minimize code rerun and to isolate the problem.

data %>% pipeline functions %>% 
   {.}-> tempWayPoint
   tmpWayPoint %>% 
more pipeline functions %>% {.} -> endPipe 
3
  • 3
    analyzedData <- data %>% analysis functions Commented Jul 19, 2015 at 22:02
  • 1
    Your title is a bit misleading; what you really want to do is interleave an assignment into a pipeline, not end it. Commented Jul 20, 2015 at 0:26
  • @Hong-Ooi I arrived here because my question was the one in the title, and indeed, that turned out not to be the question. But for others like me wanting the answer to that question, the answer is the infix function [<- (). (I can't get the backticks right; [<- is in backticks). The first argument is the object to subset and then assign (so that gets piped in), the next arguments are the subsets of the dimensions of that object (one for each), and the last is the object to assign to that subset, or overwrite it with. Commented Sep 14, 2018 at 20:47

5 Answers 5

13

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 ->

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, this seems to do the trick. Do you know the relative merits of using '{.} -> endPipe' vs 'assign("endPipe", .)' ? I see that assign allows you to specify the environment as an argument. Other than that, is one better than the other if we're only interested in assignment to the current environment? Is it just stylistic differences?
I've tried this, but the assign doesn't work. The code evaluates, but I don't get a new object called "bar".
@ccoffman You should get a new object called 'bar'. It would evaluate in the current environment so if you're doing that inside of a function and then looking for "bar" after the function exits then yeah 'bar' won't exist anymore. That's more an issue of scoping though.
I had the same problem as coffman. The code was not running in a function, as @Dason suggested. Changing the assign statement to assign("bar", .,envir = .GlobalEnv) did solve the problem though. I am using R version 3.4.1.
Using assign() in this way with pipes does not work in R 3.5.2 with marittr 1.5. Use the pos= argument to explicitly set the environment to assign the variable into (pos=1 for instance). Alternatively, follow @Wilbert and use the envir= argument.
|
7

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

Comments

5

You can think of a pipe chain as a multiline function, that works as every other multiline function. The usual way to save the output is to assign it on the first line :

analyzedData <- data %>% analysis functions

Like you would do :

plot <- ggplot(data,aes(x=x,y=x)) +
  geom_point()

1 Comment

The OP wasn't asking "how do I do an assignment?". OP was asking "If I prefer to have my assignment at the end of the pipe, how do I go about it?". As such, your answer may be seen as condescending.
4

Update: the way I figured out to do this is: data %>% do analysis %>% {.} -> analyzedData

This way, to troubleshoot / debug a long pipe, you can drop these two line into your pipe to minimize code rerun and to isolate the problem.

data %>% pipeline functions %>% 
   {.}-> tempWayPoint
   tmpWayPoint %>% 
more pipeline functions %>% {.} -> endPipe 

If you have a better way of doing this please let me know.

1 Comment

You don't need %>% {.}. You can just do pipeline_functions -> tmpWaypoint.
3

What you want also works using curly brackets such as

data %>% analysis_functions %>% {analyzedData <<-.}

And you can also extend the pipe after object assignment. I find it very handy to assign a dataframe at the end of a long chain before piping it into ggplot or saving a model object for other purposes before tidy()ing for example.

Cautionary edit: The dot notation to represent the current state of the object in the pipeline "." works only with the magrittr pipe %>% and not with the native R pipe |>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.