title: Sine curve fit using lm and nls in R
body: <p>I am a beginner in curve fitting and several posts on Stackoverflow really helped me.</p>
  
  <p>I tried to fit a sine curve to my data using <code>lm</code> and <code>nls</code> but both methods show a strange fit as shown below. Could anyone point out where I went wrong. I would suspect something to do with time but could not get it right. My data can be accessed from <a href="https://drive.google.com/file/d/0BzzExM8ZYZwxMWNpeHV0bGFBMUk/edit?usp=sharing" rel="noreferrer">here</a>.
  <img src="https://i.stack.imgur.com/qYAVN.png" alt="plot"></p>
  
  <pre><code>data &lt;- read.table(file="900days.txt", header=TRUE, sep="")
  time&lt;-data$time
  temperature&lt;-data$temperature
  
  #lm fitting
  xc&lt;-cos(2*pi*time/366)
  xs&lt;-sin(2*pi*time/366)
  fit.lm&lt;-lm(temperature~xc+xs)
  summary(fit.lm)
  plot(temp~time, data=data, xlim=c(1, 900))
  par(new=TRUE)
  plot(fit.lm$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n",
  yaxt="n")
  
  #nls fitting
  fit.nls&lt;-nls(temp~C+alpha*sin(W*time+phi),
     start=list(C=27.63415, alpha=27.886, W=0.0652, phi=14.9286))
  summary(fit.nls)
  plot(fit.nls$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n", 
  axt="n")
  </code></pre>