Search code examples
rtime-seriesmodeling

Fitting and plotting harmonic regression model of a time series in R


In R, using the HarmonicRegression library, I am trying to fit an harmonic regression model with a trend, but I am struggling to figure out how to call the harmonic.regression function and plot the fitted model.

library(TSA)    
library(HarmonicRegression)
data(tempdub)

har_model <- harmonic.regression(tempdub, time(tempdub), Tau = 24, normalize = TRUE, norm.pol = FALSE, norm.pol.degree = 1, trend.eliminate = FALSE, trend.degree = 1)

plot(ts(fitted(har_model), freq=1, start=c(1964,1)), type='l', ylim=range(c(fitted(har_model), tempdub))) 

points(tempdub)

The first error I encounter is:

Error in if (nrow(inputts) != length(inputtime)) stop(paste("Length of time series (inputts):",  : 
  argument is of length zero

Any idea how this can be achieved?


Solution

  • library("TSA")    
    library("HarmonicRegression")
    data(tempdub)
    
    har_model <- harmonic.regression(as.vector(tempdub), 
                                 1:length(tempdub), Tau = 12, 
                                 normalize = TRUE, norm.pol = FALSE, norm.pol.degree = 1, 
                                 trend.eliminate = FALSE, trend.degree = 1)
    
    
    plot(tempdub)
    lines(ts(har_model$fit.vals, freq=12, start=c(1964,1)), lty=2, col=3)
    

    https://cran.r-project.org/web/packages/HarmonicRegression/HarmonicRegression.pdf

    Manual explains that you have to supply inputts and inputtime as a vector or matrix for harmonic.regression().