(This article was first published on

**Memo's Island**, and kindly contributed to R-bloggers)Functional languages allows us to treat functions as types. This brings us a distinct advantage of being able to write a code that generates further code, this practise is generally known as metaprogramming. As a functional language R project provides tools to perform well structured code generation. In this post, I will present a simple example that generates functions on the fly based on different parametrisation in the function body. Consider the following simple function taking a vector as an argument and returning the number of element that are higher than a given threshold.

1 | myFun <- function(vec) { |

If somehow we need to have a different threshold value within the body, for a moment accept that it is a requirement rather than proposing to have an other argument in the function definition. Instead of rewriting the function by hand we will write a function that generates all these functions in our work space. Problematic bit of this exercise will be to beat lazy evalution. Here is the function that produces losts of

__type functions:__*myFun*1 | genMyFuns <- function(thresholds) { |

__explicitly there, due to lazy evalution our value for the threshold will not be assigned at the loop value but the last value of__

*substitute*__. Here is one numeric example on the R CLI session:__

*thresholds[i]*1 | > genMyFuns(c(7, 9, 10)) |

To

**leave a comment**for the author, please follow the link and comment on his blog:**Memo's Island**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...