R tips and tricks – higher-order functions

A higher-order function is a function that takes one or more functions as arguments, and\or returns a function as its result. This can be super handy in programming when you want to tilt your code towards readability and still keep it concise.

Consider the following code:

It’s also quite safe to use in that if you provide a non-existent function it would not default to some unknown behavior but will return an error:

However, this function can be also written as a sequence of if statements, like so

Using higher-order functions does not seem to create any additional computational cost:

So you can make your code more concise with little computational overhead.

2 comments on “R tips and tricks – higher-order functions”

Leave a Reply to vonjd

Your email address will not be published. Required fields are marked *