0

I want to know what the exact difference is between the R-function nls and the least squares method. I thought it was the same, but it gives different outcomes, see the example below. I want to find a power function for data (x,y). I searched the sourcecode of the function nls, but I can't find the difference. Can anyone help me?

x <- c(1,2,3,4,5,6,7,8,9,10)

y <- c(4,7,2,34,25,53,57,77,87,99)

data_xy <- data.frame(x,y)

function_nls <- nls(y ~ a*x^b, data=data_xy, start=c(a=5, b=3))

n <- length(x)

i <- seq(1,n,1)

b <- (n * sum(log(x[i])*log(y[i])) - sum(log(x[i])) * sum(log(y[i]))) / (n * sum(log(x[i])^2) - (sum(log(x[i]))^2))

a <- exp((sum(log(y[i])) - b * sum(log(x[i]))) / n)

cat(sprintf('P = %f * V ^ %f \n', a,b))

P = 2.075821 * V ^ 1.647545

coef(function_nls)

   a        b 

2.618066 1.593658

Community
  • 1
  • 1
Math Girl
  • 129
  • 8
  • NLS is Nonlinear Least Squares while PLS is Power Least Squares, the difference is already in the name, Nonlinear =/= Power. – user2974951 Sep 24 '18 at 08:52
  • Thanks for your answer @user2974951 but if I put a power function in the nls-function it will calculate PLS, right? – Math Girl Sep 24 '18 at 08:57
  • I don't see any arguments for this in the nls function. – user2974951 Sep 24 '18 at 09:06
  • @user2974951 the first argument of the nls function is a formula. If I type here a power function (a*x^b), than it is PLS right? – Math Girl Sep 24 '18 at 09:11
  • No, it's still nonlinear least squares. You have to be careful with the notation, any transformations of variables should be surrounded by `I()`, that is `I(x^power)`. Have a look at http://www.css.cornell.edu/faculty/dgr2/teach/R/R_CurveFit.pdf – user2974951 Sep 24 '18 at 09:22

0 Answers0