2

I have a function of a single variable, and various parameters.

For each value of one of the parameters (the others are fixed) there is a single root of the function. From a vector of the parameter I would like to generate a vector of the roots (using uniroot).

The actual example I'm working on is a bit messy, but I'll give it. Here are the fixed parameters:

eta_inf = -0.0139
eta_0 = 178.5
lambda = 2.4954
m = 0.83094

Here is the function:

crossFnc <- function(gamma_dot) tau - gamma_dot*(eta_inf + (eta_0-eta_inf)/(1 + (lambda*gamma_dot)^m))

Here is an example of a root for a particular value of the tau parameter:

tau=10
uniroot(crossFnc, c(0,1))$root

[1] 0.06900807

I would like to generate a vector of these roots, for example, for:

tau <- seq(0,10,length.out=101)

Thanks,

Steve

Philippe Remy
  • 2,617
  • 4
  • 20
  • 32
SteveK
  • 53
  • 5

2 Answers2

2

Maybe you could use a for loop:

my.roots <- vector()
tau.seq <- seq(0,10,length.out=101)
for (i in seq_along(tau.seq)) {
  tau <- tau.seq[i]
  my.roots[i] <- uniroot(crossFnc, c(0,1))$root
}
#> head(my.roots)
#[1] 0.000000000 0.000566379 0.001142346 0.001726677 0.002257765 0.002848007
RHertel
  • 22,694
  • 5
  • 36
  • 60
1

Make use of sapply:

# Notice the second argument
crossFnc <- function(gamma_dot, tau) { 
    tau - gamma_dot*(eta_inf + (eta_0-eta_inf)/(1 + (lambda*gamma_dot)^m))
}

# I only use length.out = 10
tau <- seq(0,10,length.out=10)

# Apply function(x) to every value in tau
myRoots <- sapply(tau, function(x) {
  uniroot(crossFnc, c(0,1), tau=x)$root 
})

myRoots

>[1] 0.000000000 0.006433349 0.013166577 0.020236503 0.027594321 0.035253401 0.043217816 0.051493442 0.060087456
>[10] 0.069008069
Martin Schmelzer
  • 22,030
  • 6
  • 65
  • 95