Title: | Function Composition in R |
---|---|
Description: | Provides a way to compose functions in R, and allows for chaining commands using the magrittr-esque forward-pipe operator, %>%. |
Authors: | Xiaofei (Susan) Wang [aut, cre], Michael Kane [aut] |
Maintainer: | Xiaofei (Susan) Wang <[email protected]> |
License: | GPL-2 |
Version: | 0.1.0 |
Built: | 2024-11-09 05:07:48 UTC |
Source: | https://github.com/swang87/fc |
The forward pipe operator behaves similar to the magrittr pipe operator with two exceptions. First, it only supports standard evaluation. If modified parameter values are needed then the 'fc' function should be used. Second, it composes functions. The return type of this operator is an R function.
lhs %>% rhs
lhs %>% rhs
lhs |
the function that will be applied second to an input. |
rhs |
the function that will be applied first to an input. |
The composed function lhs(rhs(x)).
# Create a new code block in case the pipe operator is already # defined. { # Make sure the example uses the correct pipe operator. `%>%` <- fc::`%>%` # Create a function that gets the 9th and 10th objects using the head # and tail functions. nine_and_ten <- fc(head, n=10) %>% fc(tail, n=2) nine_and_ten(iris) }
# Create a new code block in case the pipe operator is already # defined. { # Make sure the example uses the correct pipe operator. `%>%` <- fc::`%>%` # Create a function that gets the 9th and 10th objects using the head # and tail functions. nine_and_ten <- fc(head, n=10) %>% fc(tail, n=2) nine_and_ten(iris) }
'fc' is used to modify functions. It can be used to compose function with specified function parameters and it can be used to set parameter values (partial function evaluation).
fc(.func, ...)
fc(.func, ...)
.func |
the function to be modified. |
... |
the function modifiers (see Details). |
The 'fc' function works by capturing function modifier expressions in a list, which can be applied to the specified function via the 'do.call' function. The function make use of standard R evaluation only. The 'substitute' function is not used and modifiers expressions must be syntatically valid.
A modified function based on the parameters provided.
# Partial function evaluation - a function that returns the first three # elements of an object. head3 <- fc(head, n=3) # Function composition - a function that returns the fifth through the # 10th element of an object using the head and tail functions. head_1_to_10 <- fc(head, n=10) head_5_to_10 <- fc(tail, x=head_1_to_10(x)) head_5_to_10(iris)
# Partial function evaluation - a function that returns the first three # elements of an object. head3 <- fc(head, n=3) # Function composition - a function that returns the fifth through the # 10th element of an object using the head and tail functions. head_1_to_10 <- fc(head, n=10) head_5_to_10 <- fc(tail, x=head_1_to_10(x)) head_5_to_10(iris)