Predicting Future Sales in the Brazilian

E-Commerce Sector

WQD7004 (1/2023/2024) Group Assignment

Group 8 Members:

Matric Number Name
22106001 Puah Shi Shuen
23050308 Du Jingwen
22085643 Li Peijian
s2156417 Zhu Yunfeng
22108885 Lei Yinji

Introduction and Objectives

Introduction

For almost a decade, e-commerce has been gaining popularity and, in many cases, has become the main channel of relationships between sellers and customers. It has become an important economical factor for many countries. The use of e-commerce platforms was stimulated by the COVID-19 pandemic, when there was a period of social isolation. Consumption patterns and routines around the world were changed and online services such as shopping had become a necessity to supply consumer goods (Junior et al. 2023). 2018 had a 24% global growth in e-commerce, with sales of US $2.9 trillion (Amorim and Resende 2023).

The project is interested in looking at the e-commerce sector in a particular country where online shopping is prominent. With the huge increase in online shopping data, Data Science is needed more than ever to generate insights about the sector. The intention of this project is to choose a rising nation in e-commerce, as that is where the influx of data and need for analysis would be. In contrast to a nation with a fully established e-commerce sector, such as the United States, a rising nation would have less sophisticated data science tools that aim to provide added value to stakeholders involved in the sector.

Objectives

Sellers need to find a way to optimally price their products and take into account the perceived quality of their products. The sellers would need to take into account the trends of the market as well as understand consumer behavior that leads to increases and decreases in demand. Currently, there are no tools that can be found online for Brazilian e-commerce sellers to help them understand the trends in price and demand throughout the year. Having such information could help sellers with strategy planning for their business, as well as resource allocation, and potentially scaling their business through investing in more products, equipment, and manpower. Thus, a price prediction tool would be an ideal asset to have for Brazilian e-commerce sellers.

  1. To identify trends of sales in the Brazilian e-commerce sector 

  2. To find features that influences review scores, which in turn boosts seller performance

  3. To predict future sales which would ultimately help sellers optimize their strategies for sales, pricing products, and inventory management

Based on the project’s objectives, we are building two different models. One for the classification of reviews, which will provide insights to customer satisfaction and purchase behavior, and the second is the forecasting of sales trends beyond the data that we have.

In the following sections, we will do some exploration of the data set that we have (taken from Kaggle). Then, we will clean the data, and proceed to the analysis, where we will build the two models mentioned above.

Dataset Details and Exploration

We have chosen to obtain our data set from Kaggle (link). The reason for doing so is because of the convenience of access and because this data set is highly suitable for the objectives, we have laid out above. The data set that is provided by the e-commerce website itself, Olist. It is an actual commercial dataset that has over a hundred thousand orders information ranging from the years 2016 to 2018, made at multiple marketplaces in Brazil.

The primary goal is to understand the data set’s characteristics, focusing on product categories, review scores, and sales trends.

Data Loading and Initial Exploration

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.3
## 
## 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
library(ggplot2)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(caret)
## Loading required package: lattice
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
data <- read.csv('OlistMaster.csv')
category_counts <- table(data$product_category); category_counts
## 
##              agro_industry_and_commerce                        air_conditioning 
##                                     252                                     297 
##                                     art                   arts_and_craftmanship 
##                                     217                                      24 
##                                   audio                                    auto 
##                                     377                                    4356 
##                                    baby                          bed_bath_table 
##                                    3178                                   11847 
##                  books_general_interest                          books_imported 
##                                     561                                      62 
##                         books_technical                       cds_dvds_musicals 
##                                     269                                      14 
##                      christmas_supplies                              cine_photo 
##                                     148                                      74 
##                               computers                   computers_accessories 
##                                     217                                    8105 
##                          consoles_games         construction_tools_construction 
##                                    1180                                     950 
##               construction_tools_lights               construction_tools_safety 
##                                     305                                     198 
##                              cool_stuff                costruction_tools_garden 
##                                    3964                                     247 
##                 costruction_tools_tools                     diapers_and_hygiene 
##                                     101                                      39 
##                                  drinks                            dvds_blu_ray 
##                                     384                                      70 
##                             electronics                  fashio_female_clothing 
##                                    2827                                      50 
##                fashion_bags_accessories               fashion_childrens_clothes 
##                                    2159                                       8 
##                   fashion_male_clothing                           fashion_shoes 
##                                     144                                     273 
##                           fashion_sport                 fashion_underwear_beach 
##                                      31                                     143 
##                         fixed_telephony                                 flowers 
##                                     269                                      31 
##                                    food                              food_drink 
##                                     511                                     290 
##                       furniture_bedroom                         furniture_decor 
##                                     126                                    8743 
##                   furniture_living_room       furniture_mattress_and_upholstery 
##                                     522                                      41 
##                            garden_tools                           health_beauty 
##                                    4558                                    9944 
##                         home_appliances                       home_appliances_2 
##                                     823                                     268 
##                          home_comfort_2                            home_confort 
##                                      28                                     476 
##                       home_construction                              housewares 
##                                     630                                    7331 
##          industry_commerce_and_business kitchen_dining_laundry_garden_furniture 
##                                     269                                     297 
##                              la_cuisine                     luggage_accessories 
##                                      15                                    1159 
##                            market_place                                   music 
##                                     330                                      40 
##                     musical_instruments                        office_furniture 
##                                     712                                    1773 
##                          party_supplies                               perfumery 
##                                      46                                    3575 
##                                pet_shop                   security_and_services 
##                                    2020                                       2 
##                  signaling_and_security                        small_appliances 
##                                     199                                     699 
##   small_appliances_home_oven_and_coffee                          sports_leisure 
##                                      78                                    8942 
##                              stationery                  tablets_printing_image 
##                                    2607                                      85 
##                               telephony                                    toys 
##                                    4692                                    4246 
##                           watches_gifts 
##                                    6161

This code loads the ‘OlistMaster.csv’ file and calculates the count of each product category. It helps in identifying the distribution of products across various categories. Initial exploration reveals the data set’s structure and the variety of product categories it contains. Understanding the distribution of product categories is crucial for further analysis.

We can also take a look at some of the data, so that we understand what we are dealing with:

head(data)
##                           order_id                      customer_id
## 1 e481f51cbdc54678b7cc49136f2d6af7 9ef432eb6251297304e76186b10a928d
## 2 e481f51cbdc54678b7cc49136f2d6af7 9ef432eb6251297304e76186b10a928d
## 3 e481f51cbdc54678b7cc49136f2d6af7 9ef432eb6251297304e76186b10a928d
## 4 128e10d95713541c87cd1a2e48201934 a20e8105f23924cd00833fd87daa0831
## 5 0e7e841ddf8f8f2de2bad69267ecfbcf 26c7ac168e1433912a51b924fbd34d34
## 6 bfc39df4f36c3693ff3b63fcbea9e90a 53904ddbea91e1e92b2b3f1d09a7af86
##   order_status      order_purchase_timestamp             order_approved_at
## 1    delivered 2017-10-02 10:56:33.000000000 2017-10-02 11:07:15.000000000
## 2    delivered 2017-10-02 10:56:33.000000000 2017-10-02 11:07:15.000000000
## 3    delivered 2017-10-02 10:56:33.000000000 2017-10-02 11:07:15.000000000
## 4    delivered 2017-08-15 18:29:31.000000000 2017-08-15 20:05:16.000000000
## 5    delivered 2017-08-02 18:24:47.000000000 2017-08-02 18:43:15.000000000
## 6    delivered 2017-10-23 23:26:46.000000000 2017-10-25 02:14:11.000000000
##    order_delivered_carrier_date order_delivered_customer_date
## 1 2017-10-04 19:55:00.000000000 2017-10-10 21:25:13.000000000
## 2 2017-10-04 19:55:00.000000000 2017-10-10 21:25:13.000000000
## 3 2017-10-04 19:55:00.000000000 2017-10-10 21:25:13.000000000
## 4 2017-08-17 15:28:33.000000000 2017-08-18 14:44:43.000000000
## 5 2017-08-04 17:35:43.000000000 2017-08-07 18:30:01.000000000
## 6 2017-10-27 16:48:46.000000000 2017-11-07 18:04:59.000000000
##   order_estimated_delivery_date delivery_duration delivery_hours order_item_id
## 1 2017-10-18 00:00:00.000000000   6 days 01:30:13      145.50361             1
## 2 2017-10-18 00:00:00.000000000   6 days 01:30:13      145.50361             1
## 3 2017-10-18 00:00:00.000000000   6 days 01:30:13      145.50361             1
## 4 2017-08-28 00:00:00.000000000   0 days 23:16:10       23.26944             1
## 5 2017-08-15 00:00:00.000000000   3 days 00:54:18       72.90500             1
## 6 2017-11-13 00:00:00.000000000  11 days 01:16:13      265.27028             1
##                         product_id                        seller_id
## 1 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
## 2 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
## 3 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
## 4 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
## 5 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
## 6 87285b34884572647811a353c7ac498a 3504c0cb71d7fa48d967e0e4c94d59d9
##             shipping_limit_date price freight_value
## 1 2017-10-06 11:07:15.000000000 29.99          8.72
## 2 2017-10-06 11:07:15.000000000 29.99          8.72
## 3 2017-10-06 11:07:15.000000000 29.99          8.72
## 4 2017-08-21 20:05:16.000000000 29.99          7.78
## 5 2017-08-08 18:37:31.000000000 29.99          7.78
## 6 2017-10-31 02:14:11.000000000 29.99         14.10
##                          review_id review_score review_comment_title
## 1 a54f0611adc9ed256b57ede6b6eb5114            4                     
## 2 a54f0611adc9ed256b57ede6b6eb5114            4                     
## 3 a54f0611adc9ed256b57ede6b6eb5114            4                     
## 4 b46f1e34512b0f4c74a72398b03ca788            4                     
## 5 dc90f19c2806f1abba9e72ad3c350073            5                     
## 6 1bafb430e498b939f258b9c9dbdff9b1            3                     
##                                                                                                                                                       review_comment_message
## 1 Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e danificada, o que ficará chato, pois se trata de um presente.
## 2 Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e danificada, o que ficará chato, pois se trata de um presente.
## 3 Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e danificada, o que ficará chato, pois se trata de um presente.
## 4                                                                                      Deveriam embalar melhor o produto. A caixa veio toda amassada e vou dar de presente. 
## 5                                                                                                             Só achei ela pequena pra seis xícaras ,mais é um bom produto\n
## 6                                                                                                                                                                           
##            review_creation_date       review_answer_timestamp
## 1 2017-10-11 00:00:00.000000000 2017-10-12 03:43:48.000000000
## 2 2017-10-11 00:00:00.000000000 2017-10-12 03:43:48.000000000
## 3 2017-10-11 00:00:00.000000000 2017-10-12 03:43:48.000000000
## 4 2017-08-19 00:00:00.000000000 2017-08-20 15:16:36.000000000
## 5 2017-08-08 00:00:00.000000000 2017-08-08 23:26:23.000000000
## 6 2017-11-08 00:00:00.000000000 2017-11-10 19:52:38.000000000
##   payment_sequential payment_type payment_installments payment_value
## 1                  1  credit_card                    1         18.12
## 2                  3      voucher                    1          2.00
## 3                  2      voucher                    1         18.59
## 4                  1  credit_card                    3         37.77
## 5                  1  credit_card                    1         37.77
## 6                  1       boleto                    1         44.09
##                 customer_unique_id customer_zipcode customer_city
## 1 7c396fd4830fd04220f754e42b4e5bff             3149     sao paulo
## 2 7c396fd4830fd04220f754e42b4e5bff             3149     sao paulo
## 3 7c396fd4830fd04220f754e42b4e5bff             3149     sao paulo
## 4 3a51803cc0d012c3b5dc8b7528cb05f7             3366     sao paulo
## 5 ef0996a1a279c26e7ecbd737be23d235             2290     sao paulo
## 6 e781fdcc107d13d865fc7698711cc572            88032 florianopolis
##   customer_state product_weight_g product_length_cm product_height_cm
## 1             SP              500                19                 8
## 2             SP              500                19                 8
## 3             SP              500                19                 8
## 4             SP              500                19                 8
## 5             SP              500                19                 8
## 6             SC              500                19                 8
##   product_width_cm product_category seller_zipcode seller_city seller_state
## 1               13       housewares           9350        maua           SP
## 2               13       housewares           9350        maua           SP
## 3               13       housewares           9350        maua           SP
## 4               13       housewares           9350        maua           SP
## 5               13       housewares           9350        maua           SP
## 6               13       housewares           9350        maua           SP
dim(data)
## [1] 115609     38
str(data)
## 'data.frame':    115609 obs. of  38 variables:
##  $ order_id                     : chr  "e481f51cbdc54678b7cc49136f2d6af7" "e481f51cbdc54678b7cc49136f2d6af7" "e481f51cbdc54678b7cc49136f2d6af7" "128e10d95713541c87cd1a2e48201934" ...
##  $ customer_id                  : chr  "9ef432eb6251297304e76186b10a928d" "9ef432eb6251297304e76186b10a928d" "9ef432eb6251297304e76186b10a928d" "a20e8105f23924cd00833fd87daa0831" ...
##  $ order_status                 : chr  "delivered" "delivered" "delivered" "delivered" ...
##  $ order_purchase_timestamp     : chr  "2017-10-02 10:56:33.000000000" "2017-10-02 10:56:33.000000000" "2017-10-02 10:56:33.000000000" "2017-08-15 18:29:31.000000000" ...
##  $ order_approved_at            : chr  "2017-10-02 11:07:15.000000000" "2017-10-02 11:07:15.000000000" "2017-10-02 11:07:15.000000000" "2017-08-15 20:05:16.000000000" ...
##  $ order_delivered_carrier_date : chr  "2017-10-04 19:55:00.000000000" "2017-10-04 19:55:00.000000000" "2017-10-04 19:55:00.000000000" "2017-08-17 15:28:33.000000000" ...
##  $ order_delivered_customer_date: chr  "2017-10-10 21:25:13.000000000" "2017-10-10 21:25:13.000000000" "2017-10-10 21:25:13.000000000" "2017-08-18 14:44:43.000000000" ...
##  $ order_estimated_delivery_date: chr  "2017-10-18 00:00:00.000000000" "2017-10-18 00:00:00.000000000" "2017-10-18 00:00:00.000000000" "2017-08-28 00:00:00.000000000" ...
##  $ delivery_duration            : chr  "6 days 01:30:13" "6 days 01:30:13" "6 days 01:30:13" "0 days 23:16:10" ...
##  $ delivery_hours               : num  145.5 145.5 145.5 23.3 72.9 ...
##  $ order_item_id                : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ product_id                   : chr  "87285b34884572647811a353c7ac498a" "87285b34884572647811a353c7ac498a" "87285b34884572647811a353c7ac498a" "87285b34884572647811a353c7ac498a" ...
##  $ seller_id                    : chr  "3504c0cb71d7fa48d967e0e4c94d59d9" "3504c0cb71d7fa48d967e0e4c94d59d9" "3504c0cb71d7fa48d967e0e4c94d59d9" "3504c0cb71d7fa48d967e0e4c94d59d9" ...
##  $ shipping_limit_date          : chr  "2017-10-06 11:07:15.000000000" "2017-10-06 11:07:15.000000000" "2017-10-06 11:07:15.000000000" "2017-08-21 20:05:16.000000000" ...
##  $ price                        : num  30 30 30 30 30 ...
##  $ freight_value                : num  8.72 8.72 8.72 7.78 7.78 ...
##  $ review_id                    : chr  "a54f0611adc9ed256b57ede6b6eb5114" "a54f0611adc9ed256b57ede6b6eb5114" "a54f0611adc9ed256b57ede6b6eb5114" "b46f1e34512b0f4c74a72398b03ca788" ...
##  $ review_score                 : int  4 4 4 4 5 3 5 4 5 2 ...
##  $ review_comment_title         : chr  "" "" "" "" ...
##  $ review_comment_message       : chr  "Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e da"| __truncated__ "Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e da"| __truncated__ "Não testei o produto ainda, mas ele veio correto e em boas condições. Apenas a caixa que veio bem amassada e da"| __truncated__ "Deveriam embalar melhor o produto. A caixa veio toda amassada e vou dar de presente. " ...
##  $ review_creation_date         : chr  "2017-10-11 00:00:00.000000000" "2017-10-11 00:00:00.000000000" "2017-10-11 00:00:00.000000000" "2017-08-19 00:00:00.000000000" ...
##  $ review_answer_timestamp      : chr  "2017-10-12 03:43:48.000000000" "2017-10-12 03:43:48.000000000" "2017-10-12 03:43:48.000000000" "2017-08-20 15:16:36.000000000" ...
##  $ payment_sequential           : int  1 3 2 1 1 1 1 1 1 1 ...
##  $ payment_type                 : chr  "credit_card" "voucher" "voucher" "credit_card" ...
##  $ payment_installments         : int  1 1 1 3 1 1 1 2 1 2 ...
##  $ payment_value                : num  18.1 2 18.6 37.8 37.8 ...
##  $ customer_unique_id           : chr  "7c396fd4830fd04220f754e42b4e5bff" "7c396fd4830fd04220f754e42b4e5bff" "7c396fd4830fd04220f754e42b4e5bff" "3a51803cc0d012c3b5dc8b7528cb05f7" ...
##  $ customer_zipcode             : int  3149 3149 3149 3366 2290 88032 8577 13060 82030 13092 ...
##  $ customer_city                : chr  "sao paulo" "sao paulo" "sao paulo" "sao paulo" ...
##  $ customer_state               : chr  "SP" "SP" "SP" "SP" ...
##  $ product_weight_g             : num  500 500 500 500 500 500 238 238 238 238 ...
##  $ product_length_cm            : num  19 19 19 19 19 19 20 20 20 20 ...
##  $ product_height_cm            : num  8 8 8 8 8 8 10 10 10 10 ...
##  $ product_width_cm             : num  13 13 13 13 13 13 15 15 15 15 ...
##  $ product_category             : chr  "housewares" "housewares" "housewares" "housewares" ...
##  $ seller_zipcode               : int  9350 9350 9350 9350 9350 9350 9350 9350 9350 9350 ...
##  $ seller_city                  : chr  "maua" "maua" "maua" "maua" ...
##  $ seller_state                 : chr  "SP" "SP" "SP" "SP" ...
summary(data)
##    order_id         customer_id        order_status      
##  Length:115609      Length:115609      Length:115609     
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##                                                          
##                                                          
##                                                          
##                                                          
##  order_purchase_timestamp order_approved_at  order_delivered_carrier_date
##  Length:115609            Length:115609      Length:115609               
##  Class :character         Class :character   Class :character            
##  Mode  :character         Mode  :character   Mode  :character            
##                                                                          
##                                                                          
##                                                                          
##                                                                          
##  order_delivered_customer_date order_estimated_delivery_date delivery_duration 
##  Length:115609                 Length:115609                 Length:115609     
##  Class :character              Class :character              Class :character  
##  Mode  :character              Mode  :character              Mode  :character  
##                                                                                
##                                                                                
##                                                                                
##                                                                                
##  delivery_hours    order_item_id     product_id         seller_id        
##  Min.   :-386.31   Min.   : 1.000   Length:115609      Length:115609     
##  1st Qu.:  97.51   1st Qu.: 1.000   Class :character   Class :character  
##  Median : 169.42   Median : 1.000   Mode  :character   Mode  :character  
##  Mean   : 220.05   Mean   : 1.195                                        
##  3rd Qu.: 285.84   3rd Qu.: 1.000                                        
##  Max.   :4924.58   Max.   :21.000                                        
##  NA's   :2392                                                            
##  shipping_limit_date     price         freight_value     review_id        
##  Length:115609       Min.   :   0.85   Min.   :  0.00   Length:115609     
##  Class :character    1st Qu.:  39.90   1st Qu.: 13.08   Class :character  
##  Mode  :character    Median :  74.90   Median : 16.32   Mode  :character  
##                      Mean   : 120.62   Mean   : 20.06                     
##                      3rd Qu.: 134.90   3rd Qu.: 21.21                     
##                      Max.   :6735.00   Max.   :409.68                     
##                                                                           
##   review_score   review_comment_title review_comment_message
##  Min.   :1.000   Length:115609        Length:115609         
##  1st Qu.:4.000   Class :character     Class :character      
##  Median :5.000   Mode  :character     Mode  :character      
##  Mean   :4.034                                              
##  3rd Qu.:5.000                                              
##  Max.   :5.000                                              
##                                                             
##  review_creation_date review_answer_timestamp payment_sequential
##  Length:115609        Length:115609           Min.   : 1.000    
##  Class :character     Class :character        1st Qu.: 1.000    
##  Mode  :character     Mode  :character        Median : 1.000    
##                                               Mean   : 1.094    
##                                               3rd Qu.: 1.000    
##                                               Max.   :29.000    
##                                                                 
##  payment_type       payment_installments payment_value      customer_unique_id
##  Length:115609      Min.   : 0.000       Min.   :    0.00   Length:115609     
##  Class :character   1st Qu.: 1.000       1st Qu.:   60.87   Class :character  
##  Mode  :character   Median : 2.000       Median :  108.05   Mode  :character  
##                     Mean   : 2.946       Mean   :  172.39                     
##                     3rd Qu.: 4.000       3rd Qu.:  189.48                     
##                     Max.   :24.000       Max.   :13664.08                     
##                                                                               
##  customer_zipcode customer_city      customer_state     product_weight_g
##  Min.   : 1003    Length:115609      Length:115609      Min.   :    0   
##  1st Qu.:11310    Class :character   Class :character   1st Qu.:  300   
##  Median :24241    Mode  :character   Mode  :character   Median :  700   
##  Mean   :35062                                          Mean   : 2114   
##  3rd Qu.:58745                                          3rd Qu.: 1800   
##  Max.   :99980                                          Max.   :40425   
##                                                                         
##  product_length_cm product_height_cm product_width_cm product_category  
##  Min.   :  7.00    Min.   :  2.00    Min.   :  6.00   Length:115609     
##  1st Qu.: 18.00    1st Qu.:  8.00    1st Qu.: 15.00   Class :character  
##  Median : 25.00    Median : 13.00    Median : 20.00   Mode  :character  
##  Mean   : 30.31    Mean   : 16.64    Mean   : 23.11                     
##  3rd Qu.: 38.00    3rd Qu.: 20.00    3rd Qu.: 30.00                     
##  Max.   :105.00    Max.   :105.00    Max.   :118.00                     
##                                                                         
##  seller_zipcode  seller_city        seller_state      
##  Min.   : 1001   Length:115609      Length:115609     
##  1st Qu.: 6429   Class :character   Class :character  
##  Median :13660   Mode  :character   Mode  :character  
##  Mean   :24516                                        
##  3rd Qu.:28605                                        
##  Max.   :99730                                        
## 

From this, we can understand that the data has 115609 rows with 38 features (columns). It has a different types of data (numeric, character, and integer).

Identifying the Most Common Product Category

To find and focus on the most common product category in the dataset:

most_common_category <- names(which.max(category_counts))
most_common_count <- max(category_counts)
list(most_common_category, most_common_count)
## [[1]]
## [1] "bed_bath_table"
## 
## [[2]]
## [1] 11847
filtered_data <- data[data$product_category == most_common_category, ]

We see that the most common category is bed_bath_table. We will focus on analyzing the review scores of this category, as this eliminates the complexity of the model, as well as allow us to focus on the goal: which is to classify the reviews.

We will write this filtered data into a new file:

write.csv(filtered_data, "max.csv", row.names = FALSE)

The most_common_category identifies the most common product category and filters the dataset to include only data from this category. The filtered data is then saved to a new file ‘max.csv’. This step narrows down the dataset to a specific product category, allowing for a more focused analysis.

We can take a look at the dimension of the filtered data and the first few rows:

dim(filtered_data)
## [1] 11847    38
head(filtered_data)
##                              order_id                      customer_id
## 5403 5ff96c15d0b717ac6ad1f3d77225a350 19402a48fe860416adf93348aba37740
## 5404 270cd1874ca5310906e251407490d66c fce5e90c12f6f040a4a77008ebeca230
## 5405 3dcab1487bcd1dbcc6c968fdfe0511fb fbbd7759305c446d285fa335394e4809
## 5406 224bad763c3bcc7aea8ca8f87fce6608 994901274206b0378c729c1c2146e3c6
## 5407 e0e3cde1bd7f993b460771481843727f c30def9299a42a45fc635a77f7aa8d10
## 5408 20824f4d96365315a1f191746a385a0c 4fb548a2a29046f4b1d54477725ee8d3
##      order_status order_purchase_timestamp   order_approved_at
## 5403    delivered      2018-07-25 17:44:10 2018-07-25 17:55:14
## 5404    delivered      2018-03-23 16:25:13 2018-03-24 16:27:49
## 5405    delivered      2018-02-04 21:19:44 2018-02-04 21:35:23
## 5406    delivered      2018-01-10 17:48:48 2018-01-11 17:39:20
## 5407    delivered      2018-04-15 13:42:02 2018-04-15 13:55:19
## 5408    delivered      2018-05-22 22:24:43 2018-05-22 22:38:03
##      order_delivered_carrier_date order_delivered_customer_date
## 5403          2018-07-26 13:16:00           2018-07-30 15:52:25
## 5404          2018-03-27 05:48:44           2018-04-02 17:43:08
## 5405          2018-02-05 21:33:42           2018-02-06 15:42:58
## 5406          2018-01-12 21:41:42           2018-01-17 18:02:51
## 5407          2018-04-16 18:46:35           2018-04-24 18:32:48
## 5408          2018-05-23 13:04:00           2018-06-04 18:17:30
##      order_estimated_delivery_date delivery_duration delivery_hours
## 5403           2018-08-08 00:00:00   4 days 02:36:25       98.60694
## 5404           2018-04-11 00:00:00   6 days 11:54:24      155.90667
## 5405           2018-03-01 00:00:00   0 days 18:09:16       18.15444
## 5406           2018-01-31 00:00:00   4 days 20:21:09      116.35250
## 5407           2018-05-09 00:00:00   7 days 23:46:13      191.77028
## 5408           2018-06-08 00:00:00  12 days 05:13:30      293.22500
##      order_item_id                       product_id
## 5403             1 10adb53d8faa890ca7c2f0cbcb68d777
## 5404             1 10adb53d8faa890ca7c2f0cbcb68d777
## 5405             2 10adb53d8faa890ca7c2f0cbcb68d777
## 5406             1 10adb53d8faa890ca7c2f0cbcb68d777
## 5407             3 10adb53d8faa890ca7c2f0cbcb68d777
## 5408             1 10adb53d8faa890ca7c2f0cbcb68d777
##                             seller_id shipping_limit_date price freight_value
## 5403 1900267e848ceeba8fa32d80c1a5f5a8 2018-07-27 17:55:14  19.9         12.80
## 5404 1900267e848ceeba8fa32d80c1a5f5a8 2018-03-29 16:27:49  19.9         12.79
## 5405 1900267e848ceeba8fa32d80c1a5f5a8 2018-02-08 21:31:08  19.9          3.49
## 5406 1900267e848ceeba8fa32d80c1a5f5a8 2018-01-17 17:39:20  19.9         11.85
## 5407 1900267e848ceeba8fa32d80c1a5f5a8 2018-04-19 13:55:19  19.9          4.48
## 5408 1900267e848ceeba8fa32d80c1a5f5a8 2018-05-28 22:38:03  19.9         12.79
##                             review_id review_score review_comment_title
## 5403 346e42116863ea64d51cef464d8f0c9c            5                     
## 5404 fe864e7a7b491964de2537066b1413c7            5                     
## 5405 147b25708597b86b84186668cf8b366a            2                     
## 5406 aa3755cc9f46f34033618926f3a3288a            5                     
## 5407 49eb2f96f5447945d425fa49bddd5f4a            1                     
## 5408 1937557c43952cfaafa9474b8a0a0f2d            5     super recomendo 
##                           review_comment_message review_creation_date
## 5403                                              2018-07-31 00:00:00
## 5404                                              2018-04-03 00:00:00
## 5405 Chegou apenas um dos produtos que comprei.   2018-02-07 00:00:00
## 5406                                 Otima loja.  2018-01-18 00:00:00
## 5407                                              2018-04-25 00:00:00
## 5408     Parabéns pela respeito ao consumidor !   2018-06-05 00:00:00
##      review_answer_timestamp payment_sequential payment_type
## 5403     2018-08-02 21:15:12                  1  credit_card
## 5404     2018-04-03 21:06:47                  1  credit_card
## 5405     2018-02-09 18:29:24                  1  credit_card
## 5406     2018-01-21 11:12:14                  1  credit_card
## 5407     2018-04-25 22:18:18                  1  credit_card
## 5408     2018-06-06 16:48:38                  1  credit_card
##      payment_installments payment_value               customer_unique_id
## 5403                    3         32.70 e2dfa3127fedbbca9707b36304996dab
## 5404                    3         32.69 2a6ef69674d6f28002c72b8d123b3a27
## 5405                    1         65.74 1aa85e14d63e3f290326d01b5f1b106b
## 5406                    3         31.75 1136d74a0592e975b5be3035d78c6e7c
## 5407                    5        180.04 053ee39e5fff8053a860892cbd54d1ed
## 5408                    3         32.69 9987f41c2041e5225f9813f3dfb1c755
##      customer_zipcode         customer_city customer_state product_weight_g
## 5403             4812             sao paulo             SP              200
## 5404            13033              campinas             SP              200
## 5405             1452             sao paulo             SP              200
## 5406            15061 sao jose do rio preto             SP              200
## 5407             4235             sao paulo             SP              200
## 5408            11530               cubatao             SP              200
##      product_length_cm product_height_cm product_width_cm product_category
## 5403                16                10               16   bed_bath_table
## 5404                16                10               16   bed_bath_table
## 5405                16                10               16   bed_bath_table
## 5406                16                10               16   bed_bath_table
## 5407                16                10               16   bed_bath_table
## 5408                16                10               16   bed_bath_table
##      seller_zipcode seller_city seller_state
## 5403          14940    ibitinga           SP
## 5404          14940    ibitinga           SP
## 5405          14940    ibitinga           SP
## 5406          14940    ibitinga           SP
## 5407          14940    ibitinga           SP
## 5408          14940    ibitinga           SP

Now, we have reduced our file to only one product category, and 11,847 rows.

Data Cleaning

Checking for Missing Values

new_data <- read.csv("max.csv")
# Checking for missing values in the data set
missing_values <- sapply(new_data, function(x) sum(is.na(x)))

# Displaying columns with missing values if any
missing_values[missing_values > 0]
## delivery_hours 
##            162
# Dropping rows where 'order_delivered_customer_date' is missing since it's crucial for delivery time calculations
cleaned_data <- new_data[!is.na(new_data$order_delivered_customer_date), ]

# Checking the dimensions of the cleaned data
dim(cleaned_data)
## [1] 11847    38

It seems like there are no missing values with the new data, yielding us the same amount of rows and columns as previously. Now, we do not need all the columns for our analysis. For example, we do not need the review comments in free text, we also do not need to know the review ID as we will only use the numerical review score. Variables such as order_item_id also do not provide us with additional information for our analyses and models.

Thus, we will proceed to drop a few columns:

cleaned_data <- cleaned_data[, -which(names(cleaned_data) %in% c("order_status","order_approved_at","review_id","review_comment_title","order_item_id"))]

And finally, for the rest of our analysis, we have the following data frame:

dim(cleaned_data)
## [1] 11847    33

Standardizing Date Format

The dates in the data are important to us because we want to be able to forecast sales trends later on. It is also important that they are formatted correctly for clarity and simplicity when applying the model. For the first model (classification), we might also get that one of the variables that has the format of a date-time is an important feature for the classifier. The format that we currently have date-time in is:

There are many zeros at the back, which we do not want. We also want to extract the month from these dates, for a simplification of the time series model later on.

# Convert "order_purchase_timestamp" to datetime
cleaned_data$order_purchase_timestamp <- as.POSIXct(cleaned_data$order_purchase_timestamp, format="%Y-%m-%d %H:%M:%S")

# Extracting the month and creating a new column "month"
cleaned_data$month <- as.numeric(format(cleaned_data$order_purchase_timestamp, "%m"))

# Displaying the first few rows to verify the new "month" column
head(cleaned_data[c("order_purchase_timestamp", "month")])
##   order_purchase_timestamp month
## 1      2018-07-25 17:44:10     7
## 2      2018-03-23 16:25:13     3
## 3      2018-02-04 21:19:44     2
## 4      2018-01-10 17:48:48     1
## 5      2018-04-15 13:42:02     4
## 6      2018-05-22 22:24:43     5

We identified and rectified any missing values in the data set in order to guarantee its consistency and completeness. Emphasis was placed on ensuring the time series data’s completeness to prevent any omissions or outliers.

Data Analysis: Classification

Review Score Analysis

To analyze the distribution of review scores within the most common product category. For this analysis only, we also want to work with a new file as we have previously isolated the most common category for this purpose. As mentioned previously, this is for the simplicity of the model (though, all categories will again be included later on. We only want to have an idea of what the general distribution may be for a given category).

review_score_distribution <- table(new_data$review_score)
dim(new_data)
## [1] 11847    38
ggplot(data = as.data.frame(review_score_distribution), aes(x = Var1, y = Freq)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(title = "Review Score Distribution", x = "Review Score", y = "Frequency") +
  theme(axis.text.x = element_text(angle = 0)) +
  theme_minimal()

Most of the reviews are towards the higher numbers, indicating that customers are generally satisfied with their purchases.

Prepare Data for Random Forest Classification

Here, we do a little bit of feature engineering, we want to enhance the data set with additional features that could be useful for predictive modeling.

# Encode review scores into categories
cleaned_data$review_category <- cut(cleaned_data$review_score, breaks = c(0, 3, 5), labels = c("Negative", "Positive"))

# Identifying all numeric features in the dataset excluding identifiers and target variable
numeric_features <- unlist(lapply(cleaned_data, is.numeric))
excluded_features <- c("review_score")  # excluding the target variable
selected_features <- names(cleaned_data)[numeric_features & !names(cleaned_data) %in% excluded_features]

By adding a ‘month’ feature extracted from the purchase timestamp (as done previously in cleaned_data), we enable an additional dimension for analysis. And encoding review scores into categories (‘Negative’, ‘Positive’) helps with our goal of classifying the reviews. These binary labels of the reviews will be our target variable.

Then, we begin building our model to classify review scores based on various features in the data set.

# Preparing the data with all numeric features
X_all_features <- cleaned_data[selected_features]

# Replace NA values with the mean of each column
X_all_features <- apply(X_all_features, 2, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))

# Convert the result back to a data frame
X_all_features <- as.data.frame(X_all_features)

# Ensure all variables are numeric
X_all_features[] <- lapply(X_all_features, as.numeric)
y_all_features <- as.factor(cleaned_data$review_category)

This step prepares the data for modeling by selecting numeric features and handling missing values.

Then, a Random Forest classifier is trained to predict review categories. This model will provide us with insights into factors influencing customer review scores and can be used for predicting review categories for new data. We have split our data into 80% training and 20% validation.

# Splitting the dataset into training and testing sets
set.seed(42)
trainIndex <- createDataPartition(y_all_features, p = .8, list = FALSE)
X_train_all <- X_all_features[trainIndex, ]
y_train_all <- y_all_features[trainIndex]
X_test_all <- X_all_features[-trainIndex, ]
y_test_all <- y_all_features[-trainIndex]

# Initialize and train a Random Forest Classifier with all features
rf_all_features <- randomForest(x = X_train_all, y = y_train_all, ntree = 100)
rf_all_features
## 
## Call:
##  randomForest(x = X_train_all, y = y_train_all, ntree = 100) 
##                Type of random forest: classification
##                      Number of trees: 100
## No. of variables tried at each split: 3
## 
##         OOB estimate of  error rate: 19.14%
## Confusion matrix:
##          Negative Positive class.error
## Negative     1288     1474  0.53367125
## Positive      340     6376  0.05062537
# Retrieve and rank feature importances from the model
importance(rf_all_features)
##                      MeanDecreaseGini
## delivery_hours              721.10610
## price                       309.45079
## freight_value               385.34216
## payment_sequential           32.04982
## payment_installments        202.17580
## payment_value               458.93081
## customer_zipcode            478.48314
## product_weight_g            301.17768
## product_length_cm           197.51733
## product_height_cm           194.08784
## product_width_cm            190.97563
## seller_zipcode              132.64875
## month                       244.83347

The model has identified the following features that are the most important predictors for positive or negative reviews, given the variables in the data set: delivery_hours, price, and freight_value. We see two of the usual suspects when comparing e-commerce and traditional shopping: the price of the item and the delivery fees (freight_value). It is usual for consumers like you and I to buy things online for the convenience, speed, cheaper prices offered, and low delivery costs - however, we cannot conclude these here definitely, as we do not have data to support our claims.

Nevertheless, the important features that the model chose are within reason. As for the class error seen in the confusion matrix (more than 50% for the “Negative” class and less than 10% for the “Positive” class), we see clearly an imbalance of data set. This can likely be attributed to the fact that, as seen in our data exploration stage, there are more positive reviews than negative ones.

For future analysis or research into this data set (and other e-commerce data set), further data balancing can be done, such as using the SMOTE technique.

Data Analysis: Trend Forecasting

library(ggplot2)
library(zoo) # for year-month conversion
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo

To analyze the sales trend over time in the Brazilian e-commerce market, we aggregate sales data by month and year, which can be visualized to observe trends over time. Note we are using the original file again as we had previously removed all other categories.

This analysis provides insights into the sales dynamics over time, which is one of the objectives of this project, helping to understand seasonal trends or growth patterns in the e-commerce market:

# Load data and convert order_purchase_timestamp to datetime
data <- read.csv('OlistMaster.csv')
data$order_purchase_timestamp <- as.POSIXct(data$order_purchase_timestamp, format="%Y-%m-%d %H:%M:%S")
data$year_month <- as.yearmon(data$order_purchase_timestamp)

# Aggregate data to get the total number of sales per month
monthly_sales <- aggregate(order_id ~ year_month, data, FUN = length)
ggplot(monthly_sales, aes(x = year_month, y = order_id)) +
  geom_line(color = "blue") +
  geom_point(color = "blue") +
  labs(title = 'Monthly Sales Trend in Brazilian E-commerce', x = 'Month', y = 'Number of Sales') +
  theme_minimal()

This plot is important as we are now aware that the overall sales that we can observe in this data set has the above distribution. It is crucial to note that there cannot be 0 sales in July 2016 and after July 2018 - but simply, that we do not have sufficient data during those before and have no data before and after those periods.

We continue with the building of our model by extracting year and month as single variables each. We also extract only the top five categories for this analysis so that we can focus on understanding the outcomes of our model.

# Feature engineering: extract information such as year, month, etc.
data$order_purchase_timestamp <- as.POSIXct(data$order_purchase_timestamp, format="%Y-%m-%d %H:%M:%S")
data$year <- as.numeric(format(data$order_purchase_timestamp, "%Y"))
data$month <- as.numeric(format(data$order_purchase_timestamp, "%m"))

# Determine the five categories of products that sell the most
top_categories <- names(sort(table(data$product_category), decreasing = TRUE)[1:5])

# Filter out the data of these five categories of goods
top_cat_data <- data[data$product_category %in% top_categories, ]
print(top_categories)
## [1] "bed_bath_table"        "health_beauty"         "sports_leisure"       
## [4] "furniture_decor"       "computers_accessories"

Finally, we will build an ARIMA model to forecast future sales trends for the top five product categories. We have chosen the ARIMA algorithm as it is a powerful tool for time series forecasting, and these insights are particularly valuable for inventory management, marketing planning, and understanding market dynamics.


For each of these categories, we aggregate sales data monthly and apply the ARIMA model to forecast future sales trends. The results are visualized as follows for each category:

# Assuming data is already loaded and top_categories are defined
for (category in top_categories) {
  # Aggregate data to get monthly sales count for each category
  cat_data <- subset(top_cat_data, product_category == category)
  ts_data <- aggregate(order_id ~ year + month, cat_data, FUN = length)
  ts_data$Date <- as.yearmon(paste(ts_data$year, ts_data$month), "%Y %m")
  ts_data <- ts_data[order(ts_data$Date), ]
  
  # ARIMA Model
  ts_data_ts <- ts(ts_data$order_id, start=c(min(ts_data$year), min(ts_data$month)), frequency=12)
  fit <- auto.arima(ts_data_ts)
  
  # Forecasting
  n_test <- 3
  forecast <- forecast(fit, h = n_test)
  
  # Plotting the results with ggplot2
  forecast_plot <- autoplot(forecast) + 
    ggtitle(paste("Forecast:", category)) +
    theme(plot.title = element_text(hjust = 0.5),  # Centering the title
          legend.position = "bottom")  # Moving legend to bottom

  print(forecast_plot)
}

Above for each of the graphs, we can see the predicted area in grey/blue. The model generally did a good job as the trend lines are continuous from the original line plot.

By adjusting the parameter “n_test”, we can adjust the number of weeks we want to display the forecast line graph of. This would achieve our third and final objective of helping e-commerce sellers optimize their strategies for sales, pricing products, and inventory management, by visualizing the sales that they may be expecting in the future.

Conclusion

In this project, we undertook a comprehensive examination of the Brazilian e-commerce sector, intending to forecast future sales patterns and provide e-commerce sellers with insights to enhance their sales strategies. Our analysis centred on the data set we obtained from Kaggle, which comprised of information pertaining to over 100,000 orders from 2016 to 2018. In brief, we have done the following steps:

This analysis not only contributes to the comprehension of the Brazilian e-commerce market’s dynamics but also helps e-commerce sellers with insights that enable them to refine their decision-making and strategy, including processes regarding logistics, pricing, products, and marketing strategies. Refinements in these areas can ultimately result in heightened customer satisfaction and improved sales efficiency.

References

Amorim, Daniel Penido de Lima, and Marcelo Resende. 2023. “Exchange Rate Pass-Through to Brazilian E-Commerce Prices.” Global Journal of Emerging Market Economies 16 (1): 25–43. https://doi.org/10.1177/09749101221149251.
Junior, Demetrio, Mathäus Dallagnol, Vanessa Martins, and Viviane Freitag. 2023. “Evaluation of e-Commerce Systems: Comparative Study Before and During the COVID-19 Pandemic.” Journal of Information Systems and Technology Management 20 (January). https://doi.org/10.4301/s1807-1775202320002.