# How to use nlm function in R

Tags:
1. Nov 15, 2016

### the_dane

I try to find out how to minimize functions i R by using nlm function:
> f<-function(x,y){x^2+y^2+10-5*x-y}
> nlm(f,0.1,0.1)

That only gives me an estimate for x. How would write the code to get x and y?

2. Nov 16, 2016

### BvU

From
nlm(f, p, ..., hessian = FALSE, typsize = rep(1, length(p)),
fscale = 1, print.level = 0, ndigit = 12, gradtol = 1e-6,
stepmax = max(1000 * sqrt(sum((p/typsize)^2)), 1000),
steptol = 1e-6, iterlim = 100, check.analyticals = TRUE)

I gather p must be an array, not just a number like 0.1

(as becomes a good fortran programmer, I know nothing of R... )

3. Nov 16, 2016

### FactChecker

Also the independent input values of the function f must be an array x of dimension the same as p. (see https://stat.ethz.ch/R-manual/R-devel/library/stats/html/nlm.html )

4. Nov 16, 2016

### FactChecker

Your code is calling nlm incorrectly. And the function is defined incorrectly for using nlm.

All the independent variables of f that nlm should manipulate should be in the array x and all their starting guess values should be in a matching array p. There are no constant parameters to pass to f.

Try something like this:
Code (Text):

# Define a function of array x.
f<-function(x){x[1]^2+x[2]^2+10-5*x[1]-x[2]}

# Initial guess values for x
p = array( c( 1, 0), dim=c(2,1) )

# Call nlm
ans <- nlm(f,p)