library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(completejourney)
## Welcome to the completejourney package! Learn more about these data
## sets at http://bit.ly/completejourney.
library(dplyr)

# Top 3 products by Income level
combined_data <- transactions_sample %>%
  inner_join(demographics)
## Joining with `by = join_by(household_id)`
top_products_by_income <- combined_data %>%
  group_by(income, product_id) %>%
  summarize(total_sales_value = sum(sales_value, na.rm = TRUE)) %>%
  arrange(desc(total_sales_value)) %>%
  group_by(income) %>%
  top_n(3)
## `summarise()` has grouped output by 'income'. You can override using the
## `.groups` argument.
## Selecting by total_sales_value
ggplot(top_products_by_income, aes(x = income, y = total_sales_value, fill = product_id)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Top 3 Products by Income Level",
       x = "Income Level",
       y = "Total Sales Value",
       fill = "Product ID")

#Average Product Qty bought by income level

# Calculate average quantity per income level
quantity_by_income <- combined_data %>%
  group_by(income) %>%
  summarize(avg_quantity = mean(quantity, na.rm = TRUE))

ggplot(quantity_by_income, aes(x = income, y = avg_quantity)) +
  geom_bar(stat = "identity", fill = "blue") +
  labs(title = "Average Product Quantity by Income Level",
       x = "Income Level",
       y = "Average Quantity")

#Average spend by income level 

combined_data_3 <- transactions_sample %>%
  inner_join(demographics)
## Joining with `by = join_by(household_id)`
#average spend by income level
spend_by_income <- combined_data_3 %>%
  group_by(income) %>%
  summarize(avg_sales = mean(sales_value, na.rm = TRUE))

ggplot(spend_by_income, aes(x = income, y = avg_sales)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(title = "Average Spend by Income Level",
       x = "Income Level",
       y = "Average Spend")