title: Perform Fourier Analysis to a Time Series in R
body: <p>I would like to perform fourier transform to a time series using R. I would like to: </p>
  
  <ol>
  <li>Get the sum of the 5th to 18th harmonics</li>
  <li>plot each wave</li>
  <li>and output as a csv file.</li>
  </ol>
  
  <p>Here's the link to the data:
  <a href="https://drive.google.com/file/d/0B9faET7Bc2o8NjhMb29obEN1aU0/view?usp=sharing" rel="noreferrer">Link to Data</a></p>
  
  <p>Here's my initial code.</p>
  
  <pre><code>dat   &lt;- read.csv("Baguio.csv",header=FALSE)
  y     &lt;- dat$V1
  ssp   &lt;-spectrum(y)
  t     &lt;- 1:73
  per   &lt;- 1/ssp$freq[ssp$spec==max(ssp$spec)]
  reslm &lt;- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t))
  rg    &lt;- diff(range(y))
  
  #blue dashed line
  plot(y~t,ylim=c(min(y)-0.1*rg,max(y)+0.1*rg))
  lines(fitted(reslm)~t,col=4,lty=2)
  
  #green line 2nd harmonics
  reslm2 &lt;- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t)+sin(4*pi/per*t)+cos(4*pi/per*t))
  lines(fitted(reslm2)~t,col=3)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/pJd7V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pJd7V.png" alt="Sample Output image"></a></p>
  
  <p>Is there a way to simplify this code? If I have to get to the 18th harmonics the equation becomes very very long. Also, I still do not know how to add the harmonics here.</p>
  
  <p>Many thanks in advance,</p>