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)