Search code examples
rmagrittr

How to use magrittr piping with multi-argument functions?


For single argument functions, it is reasonably trivial to translate "standard" R code to the magrittr pipe style.

mean(rnorm(100))

becomes

rnorm(100) %>% mean

For multi-argument functions, it isn't clear to me what the best way to proceed is. There are two cases.

Firstly, the case when additional arguments are constants. In this case, you can create an anonymous function which changes the constant values. For example:

mean(rnorm(100), trim = 0.5)

becomes

rnorm(100) %>% (function(x) mean(x, trim = 0.5))

Secondly, the case where multiple vector arguments are required. In this case, you can combine inputs into a list, and create an anonymous function that operates on list elements.

cor(rnorm(100), runif(100))

becomes

list(x = rnorm(100), y = runif(100)) %>% (function(l) with(l, cor(x, y)))  

In both cases my solutions seem clunky enough that I feel like I'm missing a better way to do this. How should I pipe multiple arguments to functions?


Solution

  • Using the pipeR package the solution for the cor-example would be:

    pipeR:

    set.seed(123)
    rnorm(100) %>>% cor(runif(100))
    
    [1] 0.05564807
    

    margrittr:

    set.seed(123)
    rnorm(100) %>% cor(y = runif(100))
    
    [1] 0.05564807
    

    There is an excellent pipeR tutorial available from the autor of the package. There's not much of a difference in this case :-)