# Best fit sinusoidal wave in r

I am working with the following data.

x <- 1:36
y <- c(6.62,6.57,6.57,6.55,6.52,6.56,6.52,6.55,6.54,6.55,6.55,6.62,6.78,6.73,6.6,6.59,6.57,6.57,6.51,6.55,6.39,6.4,6.15,6.22,6.3,6.27,6.27,6.24,6.24,6.23,6.22,6.26,6.23,6.22,6.2,6.14)


The values of y represent monthly totals spanning 3 years beginning with January. Relatively large increases of y tend to occur in January (at values of 1, 13, and 25 for x) and they fall gradually throughout the year. I would like to represent this behavior with an asymmetric sinusoidal wave that best fits the pattern. Per this thread, I experimented with the following R code.

mylm <- lm(y ~ x + sin(2*pi/24*x) + cos(2*pi/24*x))
plot(x, y)
lines(x, mylm\$fitted.values, col = "blue")


The approximation is decent, but the symmetry of the fitted wave does not capture the sudden rises in January and the gradual declines across the remaining months.

I don't know the proper vocabulary to fully articulate what kind of wave I am seeking. Perhaps a smooth triangular wave? Thanks.

The pattern you describe is not obvious, or strong. Nevertheless, to answer your question, use Fourier series like this:

library(forecast)
y <- ts(c(6.62,6.57,6.57,6.55,6.52,6.56,6.52,6.55,6.54,6.55,6.55,6.62,
6.78,6.73,6.6,6.59,6.57,6.57,6.51,6.55,6.39,6.4,6.15,6.22,
6.3,6.27,6.27,6.24,6.24,6.23,6.22,6.26,6.23,6.22,6.2,6.14),
frequency=12)
mylm <- tslm(y ~ trend + fourier(y, K=3))
plot(y, type='p')
lines(fitted(mylm), col='blue')


This is called a harmonic regression. See https://otexts.org/fpp2/useful-predictors.html#fourier-series for the details.