In the previous post, a generic bootstrapper is created using two higher order functions: closure and functional. The closure is used to set up bootstrap configuration and it returns an anonymous functional that accepts another function that fits a model -
rpart() are used as an example. Having a function as an argument enables the bootstrapper to be generic and its main benefit is to achieve succint code - in my opinion, there would be many use cases of this kind as R’s support to object oriented programming is somewhat limited.
In this post, another way of applying higher order functions is illustrated by function composition - this example is from a StackOverflow question. Two functions are under consideration:
table(). While the latter returns a contingency table, the former returns marginal proportions given a value of its margin argument - eg 1 by row and 2 by column. Before moving forward, it’d be necessary to show simple examples of these functions.
The question is how to wrap
prop.table(). Usually it can be implemented simply by adding
table() and the additional arguments within
prop.table() followed by specifying the remaining argument of
prop.table(). However the requirement is to create a function where the arguments of both the functions are as if those that were of a single function. Both the usual and requested implementations are shown below.
The following data set is provided in the question.
As the name suggests, two functions (
g()) are composed by
compose(). margin is one of the two arguments of
proc.table() and it is set to be 1. In the body, an anonymous function is set up by wrapping
f(). This function has unspecified arguments (…) and additional arguments of
table() can be specified with it. The two functions should be specified as
compose() just returns a function, not data, and it is done using
prop(). Finally this function is used within a data.table object.
Below is another implementation and it separates arguments by matching the formal of
A quick comparison between the two would be
prop() is generic while
prop.table2() is not. However the latter can be more useful where both the functions have many arguments. For example, the following doesn’t work and I haven’t found a way to separate … between the two.