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.
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.
%>% 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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With