R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ 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(tidyquant)
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend
## 
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(readxl)

bike_orderlines_tbl <- read_xlsx("bike_orderlines.xlsx")
bike_orderlines_tbl
## # A tibble: 15,644 × 13
##    order_date          order_id order_line quantity price total_price model     
##    <dttm>                 <dbl>      <dbl>    <dbl> <dbl>       <dbl> <chr>     
##  1 2011-01-07 00:00:00        1          1        1  6070        6070 Jekyll Ca…
##  2 2011-01-07 00:00:00        1          2        1  5970        5970 Trigger C…
##  3 2011-01-10 00:00:00        2          1        1  2770        2770 Beast of …
##  4 2011-01-10 00:00:00        2          2        1  5970        5970 Trigger C…
##  5 2011-01-10 00:00:00        3          1        1 10660       10660 Supersix …
##  6 2011-01-10 00:00:00        3          2        1  3200        3200 Jekyll Ca…
##  7 2011-01-10 00:00:00        3          3        1 12790       12790 Supersix …
##  8 2011-01-10 00:00:00        3          4        1  5330        5330 Supersix …
##  9 2011-01-10 00:00:00        3          5        1  1570        1570 Synapse D…
## 10 2011-01-11 00:00:00        4          1        1  4800        4800 Synapse C…
## # ℹ 15,634 more rows
## # ℹ 6 more variables: category_1 <chr>, category_2 <chr>, frame_material <chr>,
## #   bikeshop_name <chr>, city <chr>, state <chr>
sales_by_cat_2_tbl <- bike_orderlines_tbl %>%
  select(category_2, total_price) %>%
  group_by(category_2) %>%
  summarize(sales = sum(total_price)) %>%
  ungroup() %>%
  arrange(desc(sales)) %>%
  mutate(category_2 = category_2 %>% as_factor() %>% fct_rev())

sales_by_cat_2_tbl %>%
  ggplot(aes(x = sales, y = category_2)) +
  geom_point(size = 5, color = "#2c3e50") +
  labs(title = "Sales By Category 2") +
  scale_x_continuous(labels = scales::dollar_format()) +
  theme_tq() +
  expand_limits(x = 0)

plot_sales <- function(data) {
  data %>%
    ggplot(aes(x = sales, y = category_2)) +
    geom_point(size = 5, color = "#2c3e50") +
    labs(title = "Sales By Category 2") +
    scale_x_continuous(labels = scales::dollar_format()) +
    theme_tq() +
    expand_limits(x = 0)
}

sales_by_cat_2_tbl %>%
  plot_sales()

sales_by_cat_2_tbl %>% pull(category_2) %>% levels()
## [1] "Fat Bike"           "Sport"              "Cyclocross"        
## [4] "Triathalon"         "Over Mountain"      "Trail"             
## [7] "Endurance Road"     "Elite Road"         "Cross Country Race"
sales_by_cat_2_tbl %>% pull(category_2) %>% as.numeric()
## [1] 9 8 7 6 5 4 3 2 1
sales_by_cat_2_tbl %>%
  mutate(category_2 = category_2 %>% fct_rev() %>% fct_rev()) %>%
  mutate(
    label = category_2 %>% as.character(),
    value = category_2 %>% as.numeric()
  )
## # A tibble: 9 × 4
##   category_2            sales label              value
##   <fct>                 <dbl> <chr>              <dbl>
## 1 Cross Country Race 19224630 Cross Country Race     9
## 2 Elite Road         15334665 Elite Road             8
## 3 Endurance Road     10381060 Endurance Road         7
## 4 Trail               9373460 Trail                  6
## 5 Over Mountain       7571270 Over Mountain          5
## 6 Triathalon          4053750 Triathalon             4
## 7 Cyclocross          2108120 Cyclocross             3
## 8 Sport               1932755 Sport                  2
## 9 Fat Bike            1052620 Fat Bike               1
sales_by_cat_2_tbl %>%
  arrange(desc(sales)) %>%
  mutate(sales_negative = -sales) %>%
  mutate(
    category_2 = category_2 %>% fct_reorder(sales_negative),
    values     = category_2 %>% as.numeric()) %>%
  plot_sales()

sales_by_cat_2_q_tbl <- bike_orderlines_tbl %>%
  mutate(order_date = order_date %>% floor_date("quarter") %>% ymd()) %>%
  group_by(category_2, order_date) %>%
  summarise(sales = sum(total_price)) %>%
  ungroup()
## `summarise()` has grouped output by 'category_2'. You can override using the
## `.groups` argument.
sales_by_cat_2_q_tbl
## # A tibble: 180 × 3
##    category_2         order_date   sales
##    <chr>              <date>       <dbl>
##  1 Cross Country Race 2011-01-01  610060
##  2 Cross Country Race 2011-04-01 1083310
##  3 Cross Country Race 2011-07-01  609770
##  4 Cross Country Race 2011-10-01  614110
##  5 Cross Country Race 2012-01-01  731330
##  6 Cross Country Race 2012-04-01 1097010
##  7 Cross Country Race 2012-07-01 1000220
##  8 Cross Country Race 2012-10-01  532240
##  9 Cross Country Race 2013-01-01 1017470
## 10 Cross Country Race 2013-04-01 1503950
## # ℹ 170 more rows
sales_by_cat_2_q_tbl %>%
  mutate(category_2 = category_2 %>% fct_reorder2(order_date, sales)) %>%
  ggplot(aes(x = order_date, y = sales, color = category_2)) +
  geom_point() +
  geom_line() +
  facet_wrap(~ category_2) +
  theme_tq() +
  scale_color_tq() +
  scale_y_continuous(labels = scales::dollar_format(scale = 1e-6, suffix = "M"))

order_value_tbl <- bike_orderlines_tbl %>%
  select(order_id, order_line, total_price, quantity) %>%
  group_by(order_id) %>%
  summarize(
    total_quantity = sum(quantity),
    total_price    = sum(total_price)
  ) %>%
  ungroup()

order_value_tbl %>%
  ggplot(aes(x = total_quantity, y = total_price)) +
  geom_point(alpha = 0.5, size = 2) +
  geom_smooth(method = "lm", se = FALSE)
## `geom_smooth()` using formula = 'y ~ x'

revenue_by_month_tbl <- bike_orderlines_tbl %>%
  select(order_date, total_price) %>%
  mutate(year_month = floor_date(order_date, "months") %>% ymd()) %>%
  group_by(year_month) %>%
  summarize(revenue = sum(total_price)) %>%
  ungroup()

revenue_by_category_2_tbl <- bike_orderlines_tbl %>%
  select(category_2, total_price) %>%
  group_by(category_2) %>%
  summarize(revenue = sum(total_price)) %>%
  ungroup()

revenue_by_category_2_tbl %>%
  mutate(category_2 = category_2 %>% as_factor() %>% fct_reorder(revenue)) %>%
  ggplot(aes(category_2, revenue)) +
  geom_col(fill = "#2c3e50") + 
  coord_flip()

bike_orderlines_tbl %>%
  distinct(price, model, frame_material) %>%
  ggplot(aes(price, fill = frame_material)) +
  geom_histogram() +
  facet_wrap(~ frame_material, ncol = 1) +
  scale_fill_tq() +
  theme_tq()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

bike_orderlines_tbl %>%
  distinct(price, model, frame_material) %>%
  ggplot(aes(price, fill = frame_material)) +
  geom_density(alpha = 0.5) +
  # facet_wrap(~ frame_material, ncol = 1) +
  scale_fill_tq() +
  theme_tq() +
  theme(legend.position = "bottom")

unit_price_by_cat_2_tbl <- bike_orderlines_tbl %>%
  select(category_2, model, price) %>%
  distinct() %>%
  mutate(category_2 = as_factor(category_2) %>% fct_reorder(price))

unit_price_by_cat_2_tbl %>%
  ggplot(aes(category_2, price)) +
  geom_boxplot() +
  coord_flip() +
  theme_tq()

unit_price_by_cat_2_tbl %>%
  ggplot(aes(category_2, price)) +
  geom_jitter(width = 0.15, color = "#2c3e50") +
  geom_violin(alpha = 0.5) +
  coord_flip() +
  theme_tq()

revenue_by_year_tbl <- bike_orderlines_tbl %>%
  select(order_date, total_price) %>%
  mutate(year = year(order_date)) %>%
  group_by(year) %>%
  summarize(revenue = sum(total_price)) %>%
  ungroup()

revenue_by_year_tbl %>%
  # mutate(revenue_text = scales::dollar(revenue, scale = 1e-6, suffix = "M")) %>%
  ggplot(aes(year, revenue)) +
  geom_col(fill = "#2c3e50") +
  geom_smooth(method = "lm", se = FALSE) +
  geom_text(aes(label =  scales::dollar(revenue, scale = 1e-6, suffix = "M")), 
            vjust = 1.5, color = "white") +
  geom_label(label =  "Major Demand This Year",
             vjust = -0.5, 
             size  = 5,
             fill  = "#1f78b4",
             color = "white",
             fontface = "italic",
             data = revenue_by_year_tbl %>%
               filter(year %in% c(2013))) + 
  expand_limits(y = 2e7) +
  theme_tq()
## `geom_smooth()` using formula = 'y ~ x'

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.