[R] Error using nls function

John Fox j|ox @end|ng |rom mcm@@ter@c@
Sat Mar 27 21:08:57 CET 2021


Dear David,

I'm afraid that this doesn't make much sense -- that is, I expect that 
you're not doing what you intended.

First, sin(2*pi*t) and cos(2*pi*t) are each invariant:

 > sin(2*pi*t)
  [1] -2.449294e-16 -4.898587e-16 -7.347881e-16 -9.797174e-16 
-1.224647e-15 -1.469576e-15
  [7] -1.714506e-15 -1.959435e-15 -2.204364e-15 -2.449294e-15 
-9.799650e-15 -2.939152e-15
 > cos(2*pi*t)
  [1] 1 1 1 1 1 1 1 1 1 1 1 1

Second, as formulated the model is linear in the parameters.

I hope this helps,
John

John Fox, Professor Emeritus
McMaster University
Hamilton, Ontario, Canada
web: https://socialsciences.mcmaster.ca/jfox/

On 2021-03-26 8:31 a.m., David E.S. wrote:
> 
> I'm trying to fit a harmonic equation to my data, but when I'm applying the
> nls function, R gives me the following error:
> 
> Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at
> initial parameter estimates.
> 
> All posts I've seen, related to this error, are of exponential functions,
> where a linearization is used to fix this error, but in this case, I'm not
> able to solve it in this way. I tried to use other starting points but it
> still not working.
> 
> y <- c(20.91676, 20.65219, 20.39272, 20.58692, 21.64712, 23.30965, 23.35657,
> 24.22724, 24.83439, 24.34865, 23.13173, 21.96117)
> t <- c(1, 2, 3, 4 , 5 , 6, 7, 8, 9, 10, 11, 12)
> 
> 
> # Fitting function
> 
> fit <- function(x, a, b, c) {a+b*sin(2*pi*x)+c*cos(2*pi*x)}
> 
> res <- nls(y ~ fit(t, a, b, c), data=data.frame(t,y), start = list(a=1,b=0,
> c=1))
> 
> 
> 
> Can you help me? Thanks!
> 
> David
> 
> 
> 
> --
> Sent from: https://r.789695.n4.nabble.com/R-help-f789696.html
> 
> ______________________________________________
> R-help using 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.
>



More information about the R-help mailing list