Site icon R-bloggers

Time Series Clustering in R

[This article was first published on ZAHIER NASRUDIN, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
< section id="introduction" class="level2">

Introduction

< section id="load-library" class="level2">

Load library

< details open="" class="code-fold"> < summary>Code
library(tidyverse)
library(widyr)
< section id="import-data" class="level2">

Import data

< details open="" class="code-fold"> < summary>Code
store_list <- read_csv("https://raw.githubusercontent.com/zahiernasrudin/datasets/main/sample_store.csv")
year storecode sales
2022-12-01 A4P1Q1 22432
2023-01-01 A4P1Q1 22425
2023-02-01 A4P1Q1 20710
2023-03-01 A4P1Q1 23054
2023-04-01 A4P1Q1 23912
2023-05-01 A4P1Q1 22782
< section id="clustering-with-widyr" class="level2">

Clustering with widyr

Using widely_kmeans for time series clustering:

< details open="" class="code-fold"> < summary>Code
# Perform k-means clustering using widely_kmeans
cluster_group <-  store_list %>%
  widely_kmeans(item = storecode, 
                feature = year, 
                value = sales,
                k = 3)

# Join the clustering results back to the original data
store_list_with_cluster <- left_join(store_list, cluster_group)
< !-- --> < section id="evaluating-clustering-results" class="level2">

Evaluating Clustering Results

< details open="" class="code-fold"> < summary>Code
library(ggthemes)

store_list_with_cluster |> 
  ggplot(aes(x = year, y = sales, group = storecode, colour = cluster)) +
  geom_line(show.legend = F) +
  scale_y_continuous(labels = scales::comma) +
  facet_wrap(vars(cluster)) +
  scale_color_solarized()

To leave a comment for the author, please follow the link and comment on their blog: ZAHIER NASRUDIN.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version