R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
56: Time Series Analysis with forecast Package
I've seen this mistake more times than I can count: a developer gets a dataset of monthly sales or server loads and treats it like a standard regression problem. They throw it into a linear model, maybe add a trend line, and call it a "forecast." The problem is that time series data violates the most fundamental assumption of linear regression—that your observations are independent. In a time series, today's value is almost always heavily dependent on yesterday's value. If you ignore that autocorrelation, your confidence intervals are lies and your predictions will likely drift into uselessness the moment the trend shifts.
The temptation of the linear trend
Let's say we're tracking monthly electricity demand for a city. If you take the naive approach, you might just create a sequence of numbers for time and run a simple lm(). It looks great on a plot because the line cuts right through the middle of the data, but it completely ignores the "heartbeat" of the data—the seasonality. Electricity demand spikes every July and December; a linear model just sees this as "noise" or "error" around the trend line. When you use this to predict next year, you get a flat line that misses every peak and valley, leaving the grid operators completely unprepared for the summer heatwave.
# The naive way: Treating time as a simple independent variable
demand_data <- c(120, 130, 150, 170, 200, 210, 250, 240, 200, 160, 140, 130)
time_index <- 1:12
naive_model <- lm(demand_data ~ time_index)
# This ignores seasonality and autocorrelation entirely.
Letting auto.arima handle the heavy lifting
This is where the forecast package becomes your best friend. Instead of trying to manually figure out how many times to difference the data to make it stationary, or guessing which seasonal lag to use, we use auto.arima(). I prefer this approach because it systematically tests different combinations of p, d, and q parameters (the ARIMA components) and picks the one that minimizes information loss. It doesn't just look at the trend; it looks at the relationship between a point and its previous values, and its values from the same month last year.
First, you have to wrap your data in a ts() object. R needs to know the frequency—for monthly data, that's 12. Once you've done that, auto.arima() handles the math, and the forecast() function projects that logic into the future, giving you a range of probabilities rather than a single, overly-optimistic line.
library(forecast)
# Convert to a time series object with monthly frequency
demand_ts <- ts(demand_data, frequency = 12)
# Let the package find the best ARIMA parameters automatically
fit <- auto.arima(demand_ts)
# Forecast the next 6 months
future_demand <- forecast(fit, h = 6)
plot(future_demand)
Where the automation breaks
Now, I'll give you a warning: auto.arima() is powerful, but it's not a magic wand. It assumes the underlying patterns of the past will persist into the future. If your city suddenly installs a massive array of solar panels that fundamentally changes the demand curve, the model will keep predicting based on the old "heartbeat" until you feed it enough new data to override the old patterns. Also, be careful with very short datasets. If you only have six months of data and tell R the frequency is 12, the model will struggle to find a seasonal pattern because it hasn't even seen a full cycle yet. In those cases, you're better off sticking to a simple drift model or a naive seasonal forecast until you have more history to work with.
📋 Practical Task
Forecasting Quarterly Retail Revenue
You have been handed a vector representing the quarterly revenue (in millions) for a retail store over the last 3 years: revenue_vec <- c(15, 22, 28, 45, 18, 25, 31, 48, 21, 28, 35, 52).
Your task is to:
- Convert this vector into a time series object with a quarterly frequency.
- Use the
forecastpackage to automatically determine the best ARIMA model for this data. - Generate a forecast for the next 4 quarters (one full year).
- Print the forecast object to the console and identify the "Point Forecast" for the 4th quarter of the projection.
There are no comments for now.