Search code examples
rleast-squares

Least square minimization


I hope this is the right place for such a basic question. I found this and this solutions quite articulated, hence they do not help me to get the fundamentals of the procedure.
Consider a random dataset:

x <- c(1.38, -0.24, 1.72, 2.25)
w <- c(3, 2, 4, 2)

How can I find the value of μ that minimizes the least squares equation enter image description here :

The package manipulate allows to manually change with bar the model with different values of μ, but I am looking for a more precise procedure than "try manually until you do not find the best fit".

Note: If the question is not correctly posted, I would welcome constructive critics.


Solution

  • You could proceed as follows:

    optim(mean(x), function(mu) sum(w * (x - mu)^2), method = "BFGS")$par
    # [1] 1.367273
    

    Here mean(x) is an initial guess for mu.