Search code examples
rpipeline

R Pipelining functions


Is there a way to write pipelined functions in R where the result of one function passes immediately into the next? I'm coming from F# and really appreciated this ability but have not found how to do it in R. It should be simple but I can't find how. In F# it would look something like this:

let complexFunction x =
     x |> square 
     |> add 5 
     |> toString

In this case the input would be squared, then have 5 added to it and then converted to a string. I'm wanting to be able to do something similar in R but don't know how. I've searched for how to do something like this but have not come across anything. I'm wanting this for importing data because I typically have to import it and then filter. Right now I do this in multiple steps and would really like to be able to do something the way you would in F# with pipelines.


Solution

  • We can use Compose from the functional package to create our own binary operator that does something similar to what you want

    # Define our helper functions
    square <- function(x){x^2}
    add5 <- function(x){x + 5}
    
    # functional contains Compose
    library(functional)
    
    # Define our binary operator
    "%|>%" <- Compose
    
    # Create our complexFunction by 'piping' our functions
    complexFunction <- square %|>% add5 %|>% as.character
    complexFunction(1:5)
    #[1] "6"  "9"  "14" "21" "30"
    
    
    # previously had this until flodel pointed out
    # that the above was sufficient
    #"%|>%" <- function(fun1, fun2){ Compose(fun1, fun2) }
    

    I guess we could technically do this without requiring the functional package - but it feels so right using Compose for this task.

    "%|>%" <- function(fun1, fun2){
        function(x){fun2(fun1(x))}
    }
    complexFunction <- square %|>% add5 %|>% as.character
    complexFunction(1:5)
    #[1] "6"  "9"  "14" "21" "30"