Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to `pipe through a list'?

One really cool feature from the ggplot2 package that I never really exploited enough was adding lists of layers to a plot. The fun thing about this was that I could pass a list of layers as an argument to a function and have them added to the plot. I could then get the desired appearance of the plot without necessarily returning the plot from the function (whether or not this is a good idea is another matter, but it was possible).

library(ggplot2)
x <- ggplot(mtcars,
            aes(x = qsec,
                y = mpg)) 

layers <- list(geom_point(),
               geom_line(),
               xlab("Quarter Mile Time"),
               ylab("Fuel Efficiency"))

x + layers

Is there a way to do this with pipes? Something akin to:

#* Obviously isn't going to work
library(dplyr)
action <- list(group_by(am, gear),
               summarise(mean = mean(mpg),
                         sd = sd(mpg)))

mtcars %>% action
like image 872
Benjamin Avatar asked Nov 06 '15 19:11

Benjamin


People also ask

How many commands can you pipe together?

The pipe takes output from one command and uses it as input for another. And, you're not limited to a single piped command—you can stack them as many times as you like, or until you run out of output or file descriptors.

What is a pipe command line?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes.

How do you use a pipe shell?

The pipe character | is used to connect the output from one command to the input of another. > is used to redirect standard output to a file.

What is piping in Linux?

What is a Pipe in Linux? The Pipe is a command in Linux that lets you use two or more commands such that output of one command serves as input to the next. In short, the output of each process directly as input to the next one like a pipeline.


1 Answers

To construct a sequence of magrittr steps, start with .

action = . %>% group_by(am, gear) %>% summarise(mean = mean(mpg), sd = sd(mpg))

Then it can be used as imagined in the OP:

mtcars %>% action

Like a list, we can subset to see each step:

action[[1]]
# function (.) 
# group_by(., am, gear)

To review all steps, use functions(action) or just type the name:

action
# Functional sequence with the following components:
# 
#  1. group_by(., am, gear)
#  2. summarise(., mean = mean(mpg), sd = sd(mpg))
# 
# Use 'functions' to extract the individual functions. 
like image 109
Frank Avatar answered Nov 04 '22 23:11

Frank