title: Perform fft of Time Series in R
body: <p>I would like to fit waves to a time series using FFT. 
  The goal is to have plots with different harmonics and also use it to forecast n numbers of datapoints.</p>
  
  <p>The code that I'm using is based on this <a href="https://stackoverflow.com/questions/41435777/perform-fourier-analysis-to-a-time-series-in-r">answer</a> from <a href="https://stackoverflow.com/users/2874779/catastrophic-failure">@catastrophic-failure</a></p>
  
  <pre><code> nff = function(y = NULL, n = NULL, up = 10L, plot = TRUE, add = FALSE, main = NULL, ...){
    #The direct transformation
    #The first frequency is DC, the rest are duplicated
    dff = fft(y)
    #The time
    t = seq(from = 1, to = length(y))
    #Upsampled time
    nt = seq(from = 1, to = length(y)+1-1/up, by = 1/up)
    #New spectrum
    ndff = array(data = 0, dim = c(length(nt), 1L))
    ndff[1] = dff[1] #Always, it's the DC component
    if(n != 0){
      ndff[2:(n+1)] = dff[2:(n+1)] #The positive frequencies always come first
      #The negative ones are trickier
      ndff[length(ndff):(length(ndff) - n + 1)] = dff[length(y):(length(y) - n + 1)]
    }
    #The inverses
    indff = fft(ndff/as.integer(length(y)), inverse = TRUE)
    idff = fft(dff/as.integer(length(y)), inverse = TRUE)
    if(plot){
      if(!add){
        plot(x = t, y = y, xlab = "Time", ylab = "Data",
             main = ifelse(is.null(main), paste(n, "harmonics"), main), type="l", col="green")
        lines(y = Mod(idff), x = t, col = "red")
      }
      lines(y = Mod(indff), x = nt, ...)
    }
    ret = data.frame(time = nt, y = Mod(indff))
    return(ret)
  }
  </code></pre>
  
  <p>The problem for me is, since I have also negative values in my dataset, that I can´t figure out why positive values are included.</p>
  
  <p>This is the plot of the original <a href="https://drive.google.com/drive/folders/1P_oRxJW82OrdDOB8ND5Xd6I-COgGZveM?usp=sharing" rel="nofollow noreferrer">data</a></p>
  
  <p><img src="https://i.stack.imgur.com/EZ8jF.png" alt="random.x plot"></p>
  
  <p>Compared to the plot after the fft </p>
  
  <p><img src="https://i.stack.imgur.com/h3C5S.png" alt="just the positive values"></p>
  
  <p>How can I adapt the code such that the harmonics also cover the missing negative values and also how to use that to calculate (forecast) the next n time points?</p>