Search code examples
rdplyrmagrittr

How do you end a pipe with an assignment operator?


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 

Solution

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