[R] Function Help

cls59 chuck at sharpsteen.net
Mon Oct 12 02:28:51 CEST 2009

jimdare wrote:
> Hi there,
> I have created the function below:
> pirate<-function(x){
> a<-x-1; b<-a/5; c<-a-b;
> d<-c-1; e<-d/5; f<-d-e;
> g<-f-1; h<-g/5; i<-g-h;
> j<-i-1; k<-j/5; l<-j-k;
> m<-l-1; n<-m/5; o<-m-n;
> final<-o/5;
> final
> }
> I want to run this function until the output ('final') is an exact integer
> (e.g. 893.00000 rather than 893.78332).  I then need to find out what
> value of X (input) resulted in this integer.  Could someone please help? 
> I am relatively inexperienced at creating functions.
> Kind regards,
> James 

You could approach this problem by setting it up as an optimization problem
where the task is to guess the value of x such that the squared difference
between pirate(x) and your target value is minimized. The difference is
squared in order to ensure the optimizer attempts to drive the difference to
0 instead of -infinity. A function that calculates the squared difference
between any function evaluated at a point x and some target value is:

sqDiff <- function( x, funObj, target ){

  return( ( target - funObj(x) )^2 )


You can then use R's nlm() function in an attempt to discover the value of x
that results in your target value of 893. This requires specifying an
initial guess p:

nlm( sqDiff, p = 5000, funObj = pirate, target = 893 )

[1] 1.996023e-07

[1] 13634.3

[1] -3.72529e-14

[1] 1

[1] 3

The solver came up with an estimate of 13634.3 for x:

pirate( 13634.3 )
[1] 892.9996

Achieving a solution that provides the exact value of 893 is very unlikely
using numerical optimization since these techniques involve refining a
series of guesses until one of the guesses is "good enough"-- i.e. within
1*10^{-6} of your target value-- at which point the algorithm terminates.

To get an answer that provides the target number of 893 exactly you will
probably have to use a symbolic  solver-- the Ryacas or rSymPy packages
provide interfaces to computer algebra systems that may have the necessary
symbolic tools to help you here.

Good luck!


Charlie Sharpsteen
Environmental Resources Engineering
Humboldt State University
View this message in context: http://www.nabble.com/Function-Help-tp25848627p25849148.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list