Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you end a pipe with an assignment operator?

Tags:

r

dplyr

magrittr

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 
like image 343
t-kalinowski Avatar asked Jul 19 '15 22:07

t-kalinowski


People also ask

What does the %>% operator do?

The tee ( %T>% ) operator allows you to continue piping functions that normally cause termination. The compound assignment %<>% operator is used to update a value by first piping it into one or more expressions, and then assigning the result.

What package has %>% in R?

Show activity on this post. The R packages dplyr and sf import the operator %>% from the R package magrittr.

How does a pipe operator operate?

The pipe operator feeds the mtcars dataframe into the group_by function, and then the output of group_by into summarise . The outcome of this process is stored in the tibble result , shown below. Mean miles-per-gallon of vehicles in the mtcars dataset, grouped by number of engine cylinders.


1 Answers

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

like image 198
Dason Avatar answered Sep 19 '22 02:09

Dason