Is there a way to "navigate through a list"?

One really cool feature from the ggplot2 package, which I never used enough, added layer lists to the plot. The most interesting thing is that I can pass the list of layers as an argument to the function and add them to the plot. Then I could get the desired kind of plot, without necessarily returning the plot from the function (whether this is a good idea, another thing, 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 any way to do this with pipes? Something similar to:

 #* Obviously isn't going to work library(dplyr) action <- list(group_by(am, gear), summarise(mean = mean(mpg), sd = sd(mpg))) mtcars %>% action 
+8
r ggplot2 dplyr magrittr
source share
1 answer

To build a magrittr step sequence, start with .

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

It can then be used as intended in the OP:

 mtcars %>% action 

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

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

To view all the steps, use functions(action) or simply enter a 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. 
+15
source share

All Articles