Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Pipelining functions

Tags:

r

pipeline

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.

like image 229
Matthew Crews Avatar asked Nov 13 '12 00:11

Matthew Crews


People also ask

What is a pipe function in R?

Pipes are an extremely useful tool from the magrittr package 1 that allow you to express a sequence of multiple operations. They can greatly simplify your code and make your operations more intuitive. However they are not the only way to write your code and combine multiple operations.

What is use of %>% in R?

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

What does it mean to pipe a function?

A pipe function takes an n sequence of operations; in which each operation takes an argument; process it; and gives the processed output as an input for the next operation in the sequence. The result of a pipe function is a function that is a bundled up version of the sequence of operations.


1 Answers

Here is a functional programming approach using Reduce. It is in fact an example from ?Reduce

square <- function(x) x^2
add_5 <- function(x)  x+5
x <- 1:5
## Iterative function application:
Funcall <- function(f, ...) f(...)

Reduce(Funcall, list(as.character, add_5, square,x), right = TRUE)
## [1] "6"  "9"  "14" "21" "30"

Or even more simply using the functional package and Compose

This is nice as it will create the function for you

library(functional)
do_stuff <-   Compose(square,add_5,as.character )
do_stuff(1:5)
##  [1] "6"  "9"  "14" "21" "30"

I note that I would not consider either of these approaches idiomatically R ish (if that is even a phrase)

like image 52
mnel Avatar answered Sep 28 '22 20:09

mnel