Reputation: 49
The following code is solving the equation for q1 = 10, which ends up in root q2 = 170.
q1 <- 10
fun <- function(q2) 100-q1-0.5*q2-5
root <- uniroot(fun, c(0, 200))$root
However, what I want to do is writing a loop, which operates on
v <- seq(1,200,0.05)
and therefore q1 taking the different values of the vector. I have tried several options, but none is really working, feedback usually is "values and the endpoints do/do not have the same signs" or another result is that it just replicates the function with the same output for the given length of the vector.
Does anyone have any idea how to get all of the values, without manually having to insert q1=1, q1=1.05, ...?
Upvotes: 2
Views: 1194
Reputation: 44330
uniroot
provides a ...
argument that you can use to pass additional named parameters to your function. Therefore you could add q1
as an argument to fun
and pass it as a named argument to uniroot
within sapply
:
fun <- function(q1, q2) 100-q1-0.5*q2-5
sapply(seq(1, 200, 0.05), function(q1) uniroot(fun, c(-1000, 200), q1=q1)$root)
# [1] 188.0 187.9 187.8 187.7 187.6 187.5 187.4 187.3 187.2 187.1 187.0 186.9 186.8 186.7
# [15] 186.6 186.5 186.4 186.3 186.2 186.1 186.0 185.9 185.8 185.7 185.6 185.5 185.4 185.3
# ...
Note that I set wider ranges than you had in your code to avoid the "values at end points not of opposite sign" errors.
Upvotes: 3