Fit a linear trend plus seasonal dummy model and forecast a time series in base R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
In `/app/solution.R`, fit a time series with a linear trend plus a seasonal effect, forecast future values, and score accuracy using base R.
- `fit_ts_model(y, period)`: fit `y ~ t + factor(season)` with `t = 1..length(y)` and `season = ((t-1) %% period) + 1`. Return a named list: `model` (the `lm` object), `period`, `n` (length of `y`) and `fitted` (in-sample, length `n`). Call `stop()` if `period < 2`.
- `forecast_ts(fit, h)`: return a numeric vector of length `h` for time points `n+1 . n+h`, with the season cycle continuing. Call `stop()` if `h < 1`.
- `ts_metrics(actual, predicted)`: takes equal-length vectors and returns a named list with `mae`, `rmse` and `mape`, using the formulas below.
- `moving_average(x, k)`: returns a vector the same length as `x` where element `i` is `mean(x[(i-k+1):i])` and the first `k-1` elements are `NA_real_`.
```r
mae = mean(abs(actual - predicted))
rmse = sqrt(mean((actual - predicted)^2))
mape = mean(abs((actual - predicted) / actual)) * 100
```
Example:
```r
y <- c(10, 20, 30, 12, 22, 32, 14, 24, 34)
fit <- fit_ts_model(y, period = 3)
fc <- forecast_ts(fit, h = 3) # predictions for t = 10, 11, 12
length(fc) # 3
fc # 16 26 36
moving_average(c(1, 2, 3, 4), k = 2) # NA, 1.5, 2.5, 3.5
```
```hint Seasons after the data ends
`predict()` matches new rows to the fitted coefficients through the season factor. Check that future time points get their season from the same formula and that the factor has the same levels as in the fit.
```
```hint Window edges
Trace `moving_average` for `i < k` and for a `k` larger than `length(x)` before you write the loop.
```
### Constraints & Assumptions
- Base R only (`lm`, `predict`). No external packages.
- `actual` and `predicted` passed to `ts_metrics` have the same length.
### What a Strong Answer Covers
- A model with a trend term and a season factor built with a fixed level set, returning the required list fields and enforcing the input checks
- Future time points that continue both the time index and the season cycle, passed to `predict` with matching factor levels
- The three metric formulas implemented exactly, with awareness of what zero actuals do to MAPE
- A trailing moving average with `NA_real_` padding that behaves sensibly when `k` exceeds the series length
- Awareness of how many observations the model needs relative to its parameters
### Follow-up Questions
- How would you add a confidence interval to `forecast_ts`?
- Why can a linear trend plus seasonal dummy model perform poorly, and what would you use instead?
- How would you use `ts_metrics` to get an honest estimate of forecast accuracy?
Overview: Write base R functions that fit a linear trend plus seasonal dummy regression to a time series, forecast the next h points with the season cycle continuing, score forecasts with MAE, RMSE and MAPE, and compute a trailing moving average. It tests lm with factors, predict on new data and forecast evaluation.