Reputation: 49
I am extremely new to R, so the solution to this is probably relatively simple. I have the following function to calculate stopping distance for an average car:
distance <- function(mph){(2.0*(mph/60))+(0.062673*(mph^1.9862))}
And I'm plotting all stopping distances from 1 mph to 60 mph:
range = distance(1:60)
But I need to mark where the stopping distance is equal to 120 ft. I don't have any idea how this is done in R, but I'd like to write a function where, for a stoppingdistance(x), I get the maximum speed of the car in MPH. What function should I use, and is there an easy way to check if the value of distance(x) (as it's written above) is equal to a certain value?
Upvotes: 4
Views: 1633
Reputation: 37661
I know this is an old question and has an accepted answer, but I want to point out another way to accomplish this - create the inverse function. Since you have the function, it is easy to generate many x-y points over a plausible range. Then simply create the inverse function by making y be a function of x. In your example,
x = seq(0,150,0.05)
y = distance(x)
speed = approxfun(y,x)
Now let's confirm that it gives good answewrs:
speed(120)
[1] 44.63998
distance(speed(120))
[1] 120
Upvotes: 2
Reputation: 15425
One way to do it would be to find when the function -120 is equal to 0:
distance <- function(mph, dist=0){(2.0*(mph/60))+(0.062673*(mph^1.9862))-dist}
uniroot(distance, c(1, 60), dist=120)
## $root
## [1] 44.63998
##
## $f.root
## [1] -5.088982e-06
##
## $iter
## [1] 6
##
## $estim.prec
## [1] 6.103516e-05
And to see if it worked:
distance(44.63998)
## [1] 120
Upvotes: 5