We human eat different kind of foods. Similarly, functions can eat different kind of things. We’ve seen functions that eat a number, a data frame, and a vector of numbers. Today, I’m going to show you how to create functions that eat functions. By that, I mean functions that take functions as input. For example, look at the following function.
It uses a function as input (
func) and outputs another function (
function(x, f)). Notice the output function has two parameters: one is a numeric vector and the other is yet another function!
We can use
arg_func to implement a function that takes a vector of numbers and a function as inputs, and returns the elements of the vector where the input function returns the biggest value.
For example, when applying the function \(f(x)=x^2\) to the vector
-10:5, it should obtain the biggest value at
x=-10. And when appling it to
-5:5, the maximum value should happen at
x=5. Let’s see if
arg_max() gives us the same results.
arg_max() gives us the correct results. We can also implement
arg_min() in the same fashion.
Similarly, we can implement
This article is inspired by Hadley’s book “Advanced R”, which can be obtained from Amazon.