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,967
  • 4
  • 25
  • 39
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
  • 23,412
  • 5
  • 38
  • 64
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
  • 23,283
  • 6
  • 73
  • 98
  • Works! crossFnc2 <- function(gamma_dot, tau) tau - gamma_dot*(eta_inf + (eta_0-eta_inf)/(1 + (lambda*gamma_dot)^m)) sapply(tau, function(x) { + uniroot(crossFnc2, c(0,1), tau=x)$root + }) [1] 0.000000000 0.000566379 0.001142346 0.001726677 0.002257765 0.002848007 [7] 0.003427169 0.004009318 0.004594418 0.005182443 0.005773373 0.006367191 etc. Thanks! – SteveK Jul 18 '16 at 20:35