Time Series | Dataplexa

Time Series Analysis in R

Time series analysis is used when data is collected over time at regular intervals.

It helps us understand trends, seasonal patterns, and changes that happen across time.


What Is a Time Series?

A time series is a sequence of observations recorded in time order.

Examples include monthly sales, daily temperatures, yearly revenue, or hourly website traffic.


Components of a Time Series

Most time series data is made up of four main components.

  • Trend – Long-term increase or decrease
  • Seasonality – Repeating patterns over fixed periods
  • Cyclic – Long-term fluctuations
  • Irregular – Random variation

Creating a Time Series in R

In R, the ts() function is used to create time series objects.

You must specify the data, start time, and frequency.

sales <- c(120, 135, 150, 160, 155, 170)
sales_ts <- ts(sales, start = c(2023, 1), frequency = 12)
sales_ts

Plotting Time Series Data

Visualizing time series data makes patterns easier to understand.

R provides a simple plot() function for this purpose.

plot(sales_ts,
     main = "Monthly Sales",
     xlab = "Time",
     ylab = "Sales")

Checking Time Series Frequency

Frequency tells R how many observations occur in one time unit.

For example, monthly data has frequency 12 and quarterly data has frequency 4.

frequency(sales_ts)

Decomposing a Time Series

Decomposition separates a time series into its components: trend, seasonal, and random.

This helps in understanding the underlying structure of the data.

decomposed <- decompose(sales_ts)
plot(decomposed)

Moving Average

A moving average smooths out short-term fluctuations.

It makes long-term trends easier to identify.

moving_avg <- filter(sales_ts, rep(1/3, 3))
plot(moving_avg)

Why Time Series Matters

  • Used in forecasting and prediction
  • Helps identify seasonal behavior
  • Supports business and financial decisions
  • Foundation for advanced models

📝 Practice Exercises


Exercise 1

Create a time series using quarterly data.

Exercise 2

Plot a time series object.

Exercise 3

Check the frequency of a time series.

Exercise 4

Decompose a time series into components.


✅ Practice Answers


Answer 1

values <- c(200, 220, 240, 260)
ts_data <- ts(values, start = c(2022, 1), frequency = 4)
ts_data

Answer 2

plot(ts_data)

Answer 3

frequency(ts_data)

Answer 4

decompose(ts_data)

What’s Next?

In the next lesson, you will learn about Machine Learning in R, where data is used to build predictive models.