[R] Solving a simple linear equation using uniroot give error object 'x' not found

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Oct 6 17:06:35 CEST 2020


On 06/10/2020 11:00 a.m., Sorkin, John wrote:
> Colleagues,
> I am trying to learn to use uniroot to solve a simple linear equation. I define the function, prove the function and a call to the function works. When I try to use uniroot to solve the equation I get an error message,
> Error in yfu n(x,10,20) : object 'x' not found.
> 
> I hope someone can tell we how I can fix the problem
> 
>    if(!require(rootSolve)){install.packages("rootSolve")}
>    library(rootSolve)
> 
>    # Define the function
>    yfun <- function(x,diffMean,diffSE) ((abs(diffMean)-x)/diffSE)
>    # Prove the function and a call to the function work
>    yfun(10,100,10)
>    # use uniroot to find a solution to the
>    # function in the range -100 to 100
>    uniroot(yfun(x,10,20),c(-100,100))
> 
> 
> My output:
>>    # Define the function
>>    yfun <- function(x,diffMean,diffSE) ((abs(diffMean)-x)/diffSE)
>>    # Prove the function and a call to the funciton works
>>    yfun(10,100,10)
> [1] 9
>>    # use uniroot to find a solution to the
>>    # funciton in the range -100 to 100
>>    uniroot(yfun(x,10,20),c(-100,100))
> Error in yfun(x, 10, 20) : object 'x' not found

The problem is that uniroot() wants a function as first argument, and 
yfun(x,10,20) is not a function, it's the value of a function.  You can 
do it with

  uniroot(function(x) yfun(x,10,20),c(-100,100))

which creates the anonymous function

   function(x) yfun(x,10,20)

and passes that to uniroot().

Duncan Murdoch
> 
> Thank you,
> John
> 
> 
> John David Sorkin M.D., Ph.D.
> Professor of Medicine
> Chief, Biostatistics and Informatics
> University of Maryland School of Medicine Division of Gerontology and Geriatric Medicine
> Baltimore VA Medical Center
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> (Phone) 410-605-7119
> (Fax) 410-605-7913 (Please call phone number above prior to faxing)
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list