Supermarket Data Analysis with R. A practical guide for R data science... | by Soner Yıldırım | Towards Data Science

A practical guide for R data science packages
In this article, we will practice tidyverse, a collection of R packages for data science, on a supermarket sales dataset available on Kaggle. It contains sales data of different branches of a supermarket chain during a 3-month-period.
I have previously written articles on the same dataset using Pandas and SQL. I think it is a good practice to learn how a given task can be accomplished with different tools. It makes you clearly see the differences as well as the similarities between them. Furthermore, it helps to build an intuition about how the creators of such tools approach particular problems.
Let’s start by reading the dataset using the read_csv function of the readr package. The readr package is a part of tidyverse and used for reading rectangular data.
> library(readr)> supermarket <- read_csv("/home/soner/Downloads/datasets/supermarket.csv")> head(supermarket, 5)
The tabular data structure in readr is called tibble. It is similar to the dataframe in Pandas and table in SQL.
Note: It’s a simplified version of the original dataset on Kaggle. I removed column that are redundant for the analysis.
Before starting on the analysis, we should check if there is any missing value in the data. The is.na function can be used to find the number of missing values in the entire tibble or in a specific column as below.
> sum(is.na(supermarket)) #entire tibble[1] 0> sum(is.na(supermarket$branch)) #branch column[1] 0
There is no missing value in the data so we can move on.
For data manipulation tasks such as filtering, selecting, and groping, we will use the dplyr package of tidyverse. It provides several functions for efficient data analysis and manipulation.
> library(dplyr)
We may want to get a general overview of sales at each branch. The average sales amount and the number of sales at each branch can be calculated as follows:
> by_total = group_by(supermarket, branch)> summarise(by_total, avg_total = mean(total), qty = n())  branch    avg_total   qty  <chr>     <dbl>       <int>1  A         312.       3402  B         320.       3323  C         337.       328
In the first line, the observations (i.e. rows) are grouped by the branch column. Then the summarise function is used to calculate the average of the total column for each branch and also count the number of observations per group.
The C branch has both the highest average amount and the least number of sales.
We can also check the average unit price of products in each product line. Let’s also sort them in descending order to get a more structured overview. We start with grouping the rows by the prod_line column.
> by_prod <- group_by(supermarket, prod_line)
We can now calculate the average unit price for each category and sort the results based on average values.
> summarise(by_prod, avg_unitprice = mean(unit_price)) %>%+ arrange(desc(avg_unitprice))  prod_line               avg_unitprice  <chr>                           <dbl>1 Fashion accessories              57.22 Sports and travel                57.03 Food and beverages               56.04 Home and lifestyle               55.35 Health and beauty                54.96 Electronic accessories           53.6
We combine two operations in a pipe using the “%>%” . The arrange function sorts the results in ascending order by default. We change this setting by using the desc function.
Fashion accessories lead the list but the average unit prices are quite close to each other.
We may want to find out if branches make more sale on a specific day of the week. Let’s first create a column that contains the weekday of the dates. We will use the wday function of the lubridate package which makes it easier to work with dates and times in R.
> library(lubridate)> supermarket <- mutate(supermarket, week_day = wday(date))
The mutate function of the dplyr package allows for adding new columns based on existing ones. The supermarket tibble now has a new column called week_day.
We can create a bar plot to see the number of purchases per week day. Here is how a bar plot is created using the ggplot2 package under tidyverse.
> library(ggplot2)> ggplot(supermarket) + geom_bar(mapping = aes(x=week_day, color=branch), fill='white', position='dodge')
Let’s elaborate on the syntax. The ggplot function accepts the data and creates an empty graph. The second step adds a new layer on the graph based on the given mappings and plotting type. The geom_bar function creates a bar plot. The color parameter differentiates the values based on the discrete values in the given column.
The position parameter is set as “dodge” to put the bars for each category side-by-side.
Another important measure is the distribution of the total sales amounts. It gives us an overview of how much customers are likely to spend per shopping.
One option to check the distribution of a continuous variable is creating a histogram. It divides the value range into discrete bins and count the number of observations (i.e. rows) in each bin.
We can use the geom_histogram function of the ggplot2 package to create a histogram as below.
> ggplot(supermarket) + geom_histogram(mapping = aes(x=total, color=gender), bins=15, fill='white')
The gender column is passed to the color parameter to check the distribution for males and females separately. The bins parameter sets the number of bins.
The distribution of total sales amount is highly similar for males and females.
The main purpose of this article to demonstrate various R packages that help us analyze tabular data. There is, of course, much more we can to on this dataset to further explore it.
In order to improve data analysis skills, we should learn statistics and also be good at using libraries and frameworks. The best way to get better at using such tools is through practice.
Thank you for reading. Please let me know if you have any feedback.