[R] optimizing function over x,y

Ravi Varadhan rvaradhan at jhmi.edu
Sat May 23 16:07:55 CEST 2009


Look at nlminb() or optim(), in particular the option `method = "L-BFGS-B"' or the function spg() in "BB" package.

With these you can optimize over any number of variables.

Ravi. 

____________________________________________________________________

Ravi Varadhan, Ph.D.
Assistant Professor,
Division of Geriatric Medicine and Gerontology
School of Medicine
Johns Hopkins University

Ph. (410) 502-2619
email: rvaradhan at jhmi.edu


----- Original Message -----
From: Esmail <esmail.js at gmail.com>
Date: Saturday, May 23, 2009 10:01 am
Subject: [R] optimizing function over x,y
To: R mailing list <r-help at r-project.org>


> Hello all,
>  
>  I would like to maximize or minimize a given math function over a
>  specific set of values.
>  
>  I was checking out Wolfram Alpha (
>  and it can do simple optimization problems in math, such as
>  
>       maximize 15*x - x**2 over 0 to 15
>  
>       (
>  
>  which finds the maximum value and input for x in the range 0 to 15.
>  Very cool. (This is of course a very simple example).
>  
>  Reading the R documentation I found out that with R I can do this:
>  
>  
>    f<-function(x) (15*x)-x**2
>    optimize(f, c(0,15), lower=0,upper=15, maximum=TRUE)
>  
>  which works very nicely too!
>  
>  
>  What I would like to do, but what Wolfram Alpha apparently can't do
>  (according to a post in their community forum) is to maximize (or
>  minimize) functions that contain two variables, x and y, or more. So
>  for example a very simple example would be
>  
>      minimize x**2 + y**2 over x:0 to 15, y:0-12  -- this does not work
>                                                   -- though I'm 
> unclear about
>                                                   -- the correct 
> syntax too.
>  
>  Is there a way to do this in R in just a neat and easy way as R
>  optimizes a 1-D function?
>  
>  For this particular instance I am interested in the minimum of
>  
>     x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10
>  
>  so an example of this in R would be great, though in other problems
>  the range may not be identical for x and y.
>  
>  Thanks,
>  
>  Esmail
>  
>  ps: Has anyone written any programs in Python that they then have used
>       to call R functions? I am thinking of writing some of my scripts 
> in
>       Python, but then accessing some of R's functions.
>  
>  ______________________________________________
>  R-help at r-project.org mailing list
>  
>  PLEASE do read the posting guide 
>  and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list