Is there a way to maximize/minimize a custom function in R? I'm trying to minimize a custom function. It should accept five parameters and the data set and do all sorts of calculations, producing a single number as an output. I want to find a combination of five input parameters which yields smallest output of my function.
 A: I wrote a post listing a few tutorials using optim.
Here is a quote of the relevant section:

*"The combination of the R function optim and a custom created objective
function, such as a minus log-likelihood function provides a powerful tool for
parameter estimation of custom models.  

*
*Scott Brown's tutorial includes an example of
this. 

*Ajay Shah has an example 
of writing a likelihood function and then getting a maximum likelihood
estimate using optim. 

*Benjamin Bolker has great material available on the web from his book
Ecological Models and Data in R.
PDFs, Rnw, and R code for early versions of the chapters are provided on
the website.
Chapter 6 (likelihood and all that)
, 7 (the gory details of model fitting),
and 8 (worked likelihood estimation examples). 

*Brian Ripley has a set of slides on simulation and optimisation in R. 
In particular it provides a useful discussion of the various optimisation
algorithms available using optim". 
 
A: In addition to Jeromy Anglim's answer, I have some more links.
Next to optim there is another function in base R that allows for what you want: nlminb. Check ?nlminb and ?optim for examples of the usage.
There are a bunch of packages that can do optimizations. What I found most interesting were the packages optimx and, quite new, the neldermead package for different versions of the simplex algorithm.
Furthermore, you might want to have a look at the CRAN Task View on Optimization for more packages
Please note that my recommendations all assume that you have a deterministic function (i.e., no random noise). For functions that are not strictly deterministic (or too big) you would need to use algorithms such as simulated annealing or genetic algorithms. But the CRAN Task View should have what you need.
A: Is your function continuous and differentiable?  You might be able to use optim, either with user-supplied derivatives or numerically approximated ones.
