(Adding R-help back to Cc:) On Tue, 30 Jun 2020 14:44:29 +0200 Luigi Marongiu <marongiu.lu...@gmail.com> wrote:
> Ok, I tried with: > ``` > holly <- function(p) { > y = (p$a * p$x^2) / (p$b^2 + p$x^2) > return(y) > } > X = 1:60 > A = 3261 > B = 10 > X = c(8, 24, 39, 63, 89, 115, 153, 196, 242, 287, 344, > 408, 473, 546, 619, 705, 794, 891, 999, 1096, 1242, 1363, 1506, > 1648, 1753, 1851, 1987, 2101, 2219, 2328, 2425, 2575, 2646, 2698, > 2727, 2771, 2818, 2853, 2895, 2926, 2964, 2995, 3025, 3053, 3080, > 3102, 3119, 3141, 3152, 3159, 3172, 3182, 3196, 3209, 3220, 3231, > 3239, 3246, 3252, 3261) You are correct in returning a vector of residuals to minimise a sum of squares of, but X seems to be an independent variable, not a parameter to optimize, so it shouldn't be passed as such. Instead you can either close over X: X <- c(...) holly <- function(p) (p$a * X^2) / (p:b^2 + X^2) # function holly now "contains" the vector X or pass X as an argument that nls.lm will pass to your function: holly <- function(p, X) (p$a * X^2) / (p$b^2 + X^2) # nls.lm will pass the X argument to function holly O <- nls.lm(par = list(a = 3261, b = 10), fn = holly, X = X) summary(O) # Parameters: # Estimate Std. Error t value Pr(>|t|) # a 3.090e-16 4.102e-17 7.533e+00 3.72e-10 *** # b 1.000e+01 1.525e-08 6.558e+08 < 2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 3.107e-16 on 58 degrees of freedom # Number of iterations to termination: 2 # Reason for termination: Relative error between `par' and the solution # is at most `ptol'. -- Best regards, Ivan ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.