[R-sig-eco] Using R to solve for X

Philip Dixon pdixon at iastate.edu
Thu Jun 24 14:52:04 CEST 2010


Kristin,

R includes the uniroot() function that numerical finds a root of any 
function.  It finds x such that g(x) = 0, where you provide g(x).
Here's how to use it for your standard curve problem:

fs <- function(x,y) { 91.598+11.777*x-35.074*x^2+7.208*x^3 - y }
# this is the function whose root is to be found
#  the variable to be solved for is first; any others have to specified 
when fs() is called.
#  including y as an argument avoids writing separate functions for each y

# here's how to solve for one x

uniroot(fs,y=80,lower=0.2,upper=3)

$root
[1] 0.8713045

$f.root
[1] 4.49572e-05

$iter
[1] 7

$estim.prec
[1] 6.103516e-05

# lower and upper are the interval in which to search
# $root is the answer.  The rest is information about the quality of the 
numerical solution

# here's how to find 87 roots.  You need a loop, since uniroot() is not 
(to my knowledge) vectorizable

y <- read.csv('whatever.csv')
#  read a column of Y's from a spread sheet, or use any other way to get 
a column of values into R

x <- rep(0, length(y))

for (i in 1:length(x)) {
   x[i] <-  uniroot(fs,y=y[i],lower=0.2,upper=3)$root
   }

Best wishes,
Philip Dixon



More information about the R-sig-ecology mailing list