# [R] Solving an equation in R (and using a loop)

leohearn leohearn at dal.ca
Thu Oct 15 23:18:11 CEST 2009

```Hi
So, I have a dataset and I'm trying to solve for a parameter in an equation
using the dataset. Before applying more sophisticated statistical
techniques, I want to tell R to solve it out for each observation. I know I
have to use a loop for it (and I have done that before, but am a bit rusty),
but before I do that, I'm trying to get R to solve it for just one
observation, to make sure that I have that part right before applying to the
rest. However, when I do it, I get 0 for an answer, which is a valid answer,
but a trivial one. What am I doing wrong? (tips for the loop would also be
appreciated, but this is my main concern right now.)

Here's my code:
f<-function(r){1-exp(-r*b)-(1/2)*(1-exp(-r*x1)+1-exp(-r*x2))}
uniroot(f,c(0,1))\$root

r is the unknown. I've plugged in a couple numbers from my data for b, x1,
and x2 such as:
b=5500
x1=0.01
x2=10000
and
b=198000
x1=10
x2=500000
and gotten 0 both times.