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

后端 未结 5 476
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 19:02

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

5条回答
  •  臣服心动
    2021-01-31 19:29

    What I like to do (and I found this trick somewhere I can't remember) is to use {.} -> obj at the end of my pipe-chain. This way I can add extra steps to the end of the chain by just inserting a new line, and not have to re-position to -> assignment operator.

    You can also use (.) isntead of {.} but it looks a bit, odd.

    For example, instead of this:

      iris %>% 
        ddply(.(Species), summarise, 
              mean.petal = mean(Petal.Length),
              mean.sepal = mean(Sepal.Length)) -> summary
    

    Do this:

    iris %>% 
        ddply(.(Species), summarise, 
              mean.petal = mean(Petal.Length),
              mean.sepal = mean(Sepal.Length)) %>% 
        {.} -> summary
    

    It makes it easier to see where your piped data ends up. Also, while it doesn't seem like a big deal, it's easier to add another final step as you don't need to move the -> down to a new line, just add a new line before the {.} and add the step.

    Like so:

    iris %>% 
        ddply(.(Species), summarise, 
              mean.petal = mean(Petal.Length),
              mean.sepal = mean(Sepal.Length)) %>% 
        arrange(desc(mean.petal)) %>%   # just add a step here
        {.} -> summary
    

    This doesn't help with saving intermediate results though. John Paul's answer to use assign() is nice, but its a bit long to type. You need to use the . since the data isn't the first argument, you have to put the name of the new argument in ""'s, and specify the environment (pos = 1). It seems lazy on my part, but using %>% is about speed.

    So I wrapped the assign() in a little function which speeds it up a bit:

    keep <- function(x, name) {assign(as.character(substitute(name)), x, pos = 1)}
    

    So now you can do this:

      keep <- function(x, name) {assign(as.character(substitute(name)), x, pos = 1)}
    
      iris %>% 
        ddply(.(Species), summarise, 
              mean.petal = mean(Petal.Length),
              mean.sepal = mean(Sepal.Length)) %>% keep(unsorted.data) %>% # keep this step
        arrange(mean.petal) %>%
        {.} -> sorted.data
    
    sorted.data
    #     Species mean.petal mean.sepal
    #1     setosa      1.462      5.006
    #2 versicolor      4.260      5.936
    #3  virginica      5.552      6.588
    
    unsorted.data
    #     Species mean.petal mean.sepal
    #1     setosa      1.462      5.006
    #2 versicolor      4.260      5.936
    #3  virginica      5.552      6.588
    

提交回复
热议问题