I acquired data (motor adaptation $y$ as a function of delays $t$ ) which I expect to look like a sine wave. I am trying (1) to fit a sine curve in my data and (2) to estimate the best model/parameters. I read several posts here but I am sill struggling.
I tried to use nls
using the equation $y(t) = A \sin(\Omega t + \Phi) + C$ where $A$ is the amplitude, $\Omega$ the period, $\Phi$ the phase shift and $C$ the midline.
R CODE
t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)
A<- (max(y)-min(y)/2)
C<-((max(y)+min(y))/2)
res1<- nls(y ~ A*sin(omega*t+phi)+C, data=data.frame(t,y), start=list(A=A,omega=pi/2,phi=0,C=C))
summary(res1)
co <- coef(res1)
resid(res1)
sum(resid(res1)^2)
fit <- function(x, a, b, c, d) {a*sin(b*x+c)+d}
# Plot result
plot(x=t, y=y)
curve(fit(x, a=co["A"], b=co["omega"], c=co["phi"], d=co["C"]), add=TRUE ,lwd=2, col="steelblue")
OUTPUT
Formula: y ~ A * sin(omega * t + phi) + C
Parameters:
Estimate Std. Error t value Pr(>|t|)
A 0.21956 0.03982 5.513 0.0015 **
omega 2.28525 0.07410 30.841 7.72e-08 ***
phi -32.57364 0.40375 -80.678 2.44e-10 ***
C 0.41146 0.02926 14.061 8.07e-06 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.09145 on 6 degrees of freedom
Number of iterations to convergence: 18
Achieved convergence tolerance: 9.705e-06
GRAPH
QUESTIONS
-How can I improve the fit using this method? I tried to change some parameters manually but for example to change phase shift $\Phi$ does not do much or lead to an error.
Error in nls(y ~ A * sin(omega * t + phi) + C, data = data.frame(t, y), :
le pas 0.000488281 est devenu inférieur à 'minFactor' de 0.000976562