(This article was first published on

**R – William Doane**, and kindly contributed to R-bloggers)

Functions are first class objects in R. Functions establish closures also known in R as environments. So, you can use functions to create other functions in creative ways.

Here, I’ve written a function called `divisor`

that returns a function that checks whether a given input, `d`

, is evenly divisible by `number`

and if so, returns `string`

. Then I use `divisor`

to create a test for divisibility by 3 and another for divisibility by 5.

**Problem**: Given a range of positive, non-zero integers, output “Fizz” if the number is evenly divisible by 3, output “Buzz” if the number is evenly divisible by 5, and output “FizzBuzz” if the number is evenly divisible by both 3 and 5; otherwise, output the number.

**Solution**:

divisor <- function(number, string) { function(d) { if (d %% number == 0) string else "" } } mod3er <- divisor(3, "Fizz") mod5er <- divisor(5, "Buzz") fizzbuzz <- function(i) { res <- paste0(mod3er(i), mod5er(i)) ifelse(res == "", i, res) } sapply(1:100, fizzbuzz)

To

**leave a comment**for the author, please follow the link and comment on their blog:**R – William Doane**.R-bloggers.com offers

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