Reputation: 297
The example is from the rootsolve package:
We have this function:
gradient(f, x, centered = FALSE, pert = 1e-8, ...)
in which f is a function and x is the data input in for of a vector
Now the following is an instance of the code being run:
logistic <- function (x, times) {
with (as.list(x),
{
N <- K / (1+(K-N0)/N0*exp(-r*times))
return(c(N = N))
})
}
# parameters for the US population from 1900
x <- c(N0 = 76.1, r = 0.02, K = 500)
# Sensitivity function: SF: dfi/dxj at
# output intervals from 1900 to 1950
SF <- gradient(f = logistic, x, times = 0:50)
My question is how does the code understand to use times
in its routine. It's not defined globally and it is not part of the function input list either. Is it possible to pass inputs to a function when it is not defined in its structure? Does ...
play a role here?
Upvotes: 0
Views: 55
Reputation: 3253
...
is just a way of getting an extra arguments and passing them on to another function.
Simple example:
power.function <- function(x,power) { x^power }
apply.function <- function(f, data, ...) { f(data, ...) }
sample <- c(1,2,3)
apply.function (power.function, sample, power = 3)
# which is the same as
apply.function (power.function, sample, 3)
produces
> apply.function (power.function, sample, 3)
[1] 1 8 27
EDIT
To make it crystal clear, if you look at the source of the rootSolve::gradient
you'll see the definition as
function (f, x, centered = FALSE, pert = 1e-08, ...)
and further down the call to
reff <- f(x, ...)
which is the same as described above in the example.
Upvotes: 3