Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to feed the result of a pipe chain (magrittr) to an object

Tags:

r

magrittr

This is a fairly simply question. But I couldn't find the answer per google/stackexchange and looking at the documentation of magrittr. How do you feed the result of a chain of functions which are connected via %>% to create a vector?

what I saw most people do is:

a <-
data.frame( x = c(1:3), y = (4:6)) %>%
sum()

but is there also a solution where I can just pipe-chain the result to feed it to an object, maybe an alias or sth of the like, somewhat like this:

data.frame( x = c(1:3), y = (4:6)) %>%
sum() %>%
a <- ()

this would help with keeping all of the code in the same logic of feeding results forward "down the pipe".

like image 423
grrgrrbla Avatar asked Sep 22 '14 13:09

grrgrrbla


2 Answers

Try this:

data.frame( x = c(1:3), y = (4:6)) %>% sum -> a 
like image 119
G. Grothendieck Avatar answered Oct 18 '22 18:10

G. Grothendieck


You can do it like so:

data.frame( x = c(1:3), y = (4:6)) %>%  
sum %>%  
assign(x="a",value=.,pos=1)  

A couple of things to note:

You can use "." to tell magrittr which argument the object being brought forward belongs in. By default it is the first, but here I use the . to indicate that I want it in the second value argument instead.

Second I had to use the pos=1 argument to make the assignment in the global environment.

like image 31
John Paul Avatar answered Oct 18 '22 16:10

John Paul