# Load Required Packages
library(tidyr)
library(ggplot2)
library(reshape2)
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
head(data)
##                                                                             
## 1 function (..., list = character(), package = NULL, lib.loc = NULL,        
## 2     verbose = getOption("verbose"), envir = .GlobalEnv, overwrite = TRUE) 
## 3 {                                                                         
## 4     fileExt <- function(x) {                                              
## 5         db <- grepl("\\\\.[^.]+\\\\.(gz|bz2|xz)$", x)                     
## 6         ans <- sub(".*\\\\.", "", x)
names(data)
## NULL
data <- read.csv("C:/Users/Owner/Desktop/W3 - olap_sales_data.csv")
# Visualize the data

names(data)
## [1] "TransactionID"   "Region"          "ProductCategory" "Subcategory"    
## [5] "SalesAmount"     "QuantitySold"    "TransactionDate"
head(data)
##   TransactionID Region ProductCategory Subcategory SalesAmount QuantitySold
## 1        T00001  South       Furniture      Chairs      733.71            3
## 2        T00002   East            Toys Board Games      167.26            3
## 3        T00003  North        Clothing       Women     1978.40            2
## 4        T00004   West       Groceries       Dairy     1858.51            1
## 5        T00005   West       Groceries       Dairy     1098.00            6
## 6        T00006   West       Groceries     Produce     2435.62            4
##   TransactionDate
## 1      2023-07-02
## 2      2023-07-28
## 3      2023-07-26
## 4      2023-01-14
## 5      2023-04-17
## 6      2023-09-19
# Part A: Data Summarization and Aggregation 

#### Task 1: Summarize by Region  

region_summary <- data %>% 
    group_by(Region) %>%
    summarise(
        Total_Sales = sum(SalesAmount, na.rm = TRUE), 
        Total_Quantity = sum(QuantitySold, na.rm = TRUE)
    )

print(region_summary)
## # A tibble: 5 × 3
##   Region  Total_Sales Total_Quantity
##   <chr>         <dbl>          <int>
## 1 Central     288894.           1177
## 2 East        241880.           1128
## 3 North       301748.           1248
## 4 South       236509.           1077
## 5 West        234904.           1031
#### Task 2: Summarize by Product Category 

category_summary <- data %>% 
    group_by(ProductCategory) %>%
    summarise(
        Total_Sales = sum(SalesAmount, na.rm = TRUE)
    )

print(category_summary)
## # A tibble: 8 × 2
##   ProductCategory  Total_Sales
##   <chr>                  <dbl>
## 1 Books                153873.
## 2 Clothing             167450.
## 3 Electronics          151225.
## 4 Furniture            160697.
## 5 Groceries            214192.
## 6 Home Appliances      165132.
## 7 Sports Equipment     150716.
## 8 Toys                 140648.
#### Task 3: Pivot Table 

sales_pivot <- data %>%
  group_by(ProductCategory, Region) %>%
  summarise(
    Total_Sales = sum(SalesAmount, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  pivot_wider(
    names_from = Region,
    values_from = Total_Sales,
    values_fill = 0
  )

print(sales_pivot)
## # A tibble: 8 × 6
##   ProductCategory  Central   East  North  South   West
##   <chr>              <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
## 1 Books             34481. 27827. 42507. 22016. 27042.
## 2 Clothing          38829. 27226. 38463. 41633. 21299.
## 3 Electronics       26558. 28240. 45625. 21512  29290.
## 4 Furniture         38757. 32100. 37185. 36306. 16349.
## 5 Groceries         38871. 41178. 55536. 41650. 36957.
## 6 Home Appliances   34662. 23843. 38788. 30007. 37832.
## 7 Sports Equipment  50326. 19929. 28538. 19004. 32919.
## 8 Toys              26411. 41537. 15104. 24381  33215.
# Part B: OLAP operations 

#### Task 1: Slice by North Region 

north_sales <- data %>% 
    filter(Region == 'North')

north_summary <- north_sales %>%
    summarise(
        Total_Sales = sum(SalesAmount, na.rm = TRUE),
        Total_Quantity = sum(QuantitySold, na.rm = TRUE),
        Total_Transactions = n()
    )

print(north_summary)
##   Total_Sales Total_Quantity Total_Transactions
## 1    301747.7           1248                222
#### Task 2: Dice Operation - Electronics and Furniture in South and East 

dice_sales <- data %>% 
    filter(
        ProductCategory %in% c("Electronics", "Furniture"),
        Region %in% c("South", "East")
    )

dice_summary <- dice_sales %>% 
    group_by(ProductCategory, Region) %>%
    summarise(
        Total_Sales = sum(SalesAmount, na.rm = TRUE),
        Total_Quantity = sum(QuantitySold, na.rm = TRUE), 
        .groups = "drop"
    )

print(dice_summary)
## # A tibble: 4 × 4
##   ProductCategory Region Total_Sales Total_Quantity
##   <chr>           <chr>        <dbl>          <int>
## 1 Electronics     East        28240.            120
## 2 Electronics     South       21512             110
## 3 Furniture       East        32100.            142
## 4 Furniture       South       36306.            141
#### Task 3: Data Cube 

sales_cube <- data %>% 
    group_by(ProductCategory, Region) %>% 
    summarise( 
        Total_Sales = sum(SalesAmount, na.rm = TRUE),
        Total_Quantity = sum(QuantitySold, na.rm = TRUE), 
        .groups = "drop"
        )

print(sales_cube)
## # A tibble: 40 × 4
##    ProductCategory Region  Total_Sales Total_Quantity
##    <chr>           <chr>         <dbl>          <int>
##  1 Books           Central      34481.            154
##  2 Books           East         27827.            115
##  3 Books           North        42507.            141
##  4 Books           South        22016.            143
##  5 Books           West         27042.            121
##  6 Clothing        Central      38829.            149
##  7 Clothing        East         27226.            117
##  8 Clothing        North        38463.            158
##  9 Clothing        South        41633.            144
## 10 Clothing        West         21299.             87
## # ℹ 30 more rows
# Part C: Visualization and Insights

#### Task 1: Sales by product category

ggplot(category_summary, 
       aes(x = ProductCategory,
           y = Total_Sales,
           fill = ProductCategory)) + 
    geom_col() + 
    labs(
        title = "Total Sales By Product Category", 
        x = "Product Category", 
        y = "Total Sales"
        ) + 
    theme_minimal() +
    theme(legend.position = "none")

#### Sales by region 

ggplot(region_summary, 
       aes(x = Region,
           y = Total_Sales,
           fill = Region)) + 
    geom_col() +
    labs(
        title = "Total Sales By Region", 
        x = "Region", 
        y = "Total Sales"
    ) + 
    theme_minimal() +
    theme(legend.position = "none")

#### Task 2: Generate Heat Map

ggplot(sales_cube, 
       aes(x = Region, 
           y = ProductCategory, 
           fill = Total_Sales)) + 
    geom_tile(color = "white") + 
    scale_fill_gradient(
        low = "lightblue", 
        high = "darkblue"
    ) +
    labs(
        title = "Retail Sales Heatmap", 
        x = "Region", 
        y = "Product Category", 
        fill = "Total Sales"
    ) + 
    theme_minimal() + 
    theme(legend.position = "none")

#### Task 3: Reflect on how OLAP operations support decision-making in retail analytics scenarios

##### OLAP operations are crucial for analysis as it allows large data sets to be organized, summarized, and analyzed from different perspectives. The slice operation helps a company focus on a specific category such as total sales or region, whereas the dice operation allows an analyst to explore multiple different categories together in combination. Data cubes provide a multidimensional view of the data making it easier to observe the data and identify trends. Visualizations such as bar charts and heat maps make it easier to understand and interpret the data for both the company and the public if they wish to publish any of their findings. Retailers can use insights found by OLAP operations and visualizations to make more informed company decisions such as inventory management, identifying popular products, and evaluating regional performance among many others. Overall OLAP operations help transform raw sales data into data that can be used to make data-driven marketing decisions and improve a companies outlook.