Scenario

I am a junior data analyst working in the marketing analyst team at Cyclistic, a bike-share company in Chicago. The director of marketing believes the company’s future success depends on maximizing the number of annual memberships. Therefore, my team wants to understand how casual riders and annual members use Cyclistic bikes differently. From these insights, my team will design a new marketing strategy to convert casual riders into annual members. But first, Cyclistic executives must approve my recommendations, so they must be backed up with compelling data insights and professional data visualizations.

Analysis

This is the analyze phase of the data analysis process. The data was collected from https://divvy-tripdata.s3.amazonaws.com/index.html which contains a lot of data sets from various years collected over time and stored either on monthly or quarterly basis. For this particular case study, I will be using the 2022 monthly data set. The data set was downloaded for each month into my local pc, unzipped, stored in a new folder.

Cyclistic_Exercise_Full_Year_Analysis

This analysis is for case study 1 from the Google Data Analytics Certificate (Cyclistic). It’s originally based on the case study “‘Sophisticated, Clear, and Polished’: Divvy and Data Visualization” written by Kevin Hartman (found here: https://artscience.blog/home/divvy-dataviz-case-study). I will be using the Divvy dataset for the case study. The purpose of this script is to consolidate downloaded Divvy data into a single dataframe and then conduct simple analysis to help answer the key question: “In what ways do members and casual riders use Divvy bikes differently?”

Loading libraries.

Since I have already installed the libraries on my R studio, I will just load them up before I commence

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.3     ✔ 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(lubridate)
library(dplyr)
  • library(tidyverse) helps wrangle data
  • library(lubridate) helps wrangle date attributes
  • library(dplyr) helps wrangle data too for example, filter, summarize etc.

Working directory

You can use the getwd() to get your work directory or setwd() to set it

STEP 1: COLLECT DATA

Upload Divvy datasets (csv files) here

jan22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202201-divvy-tripdata.csv")
feb22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202202-divvy-tripdata.csv")
mar22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202203-divvy-tripdata.csv")
apr22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202204-divvy-tripdata.csv")
may22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202205-divvy-tripdata.csv")
jun22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202206-divvy-tripdata.csv")
jul22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202207-divvy-tripdata.csv")
aug22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202208-divvy-tripdata.csv")
sep22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202209-divvy-tripdata.csv")
oct22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202210-divvy-tripdata.csv")
nov22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202211-divvy-tripdata.csv")
dec22 <- read.csv("C:/Users/Admin/Documents/data_projects/cyclistic_2022/cyclistic_xlxs_2022/202212-divvy-tripdata.csv")

View the imported dataset

View(jan22)
View(feb22)
View(mar22)
View(apr22)
View(may22)
View(jun22)
View(jul22)
View(aug22)
View(sep22)
View(oct22)
View(nov22)
View(dec22)

After going through the datasets, I noticed some inconsistencies with the datetime at columns started_at and ended_at. So I correct them using the as.POSIXct function which is a base R function used to convert date and time.

Change the datatype of started_at and ended_at

jan22$started_at <- as.POSIXct(jan22$started_at, format = "%d/%m/%Y %H:%M" )
jan22$ended_at <- as.POSIXct(jan22$ended_at, format = "%d/%m/%Y %H:%M" )
feb22$started_at <- as.POSIXct(feb22$started_at, format = "%d/%m/%Y %H:%M" )
feb22$ended_at <- as.POSIXct(feb22$ended_at, format = "%d/%m/%Y %H:%M" )
dec22$started_at <- as.POSIXct(dec22$started_at, format = "%d/%m/%Y %H:%M" )
dec22$ended_at <- as.POSIXct(dec22$ended_at, format = "%d/%m/%Y %H:%M" )
mar22$started_at <- as.POSIXct(mar22$started_at, format = "%Y-%m-%d %H:%M:" )
mar22$ended_at <- as.POSIXct(mar22$ended_at, format = "%Y-%m-%d %H:%M:" )
apr22$started_at <- as.POSIXct(apr22$started_at, format = "%Y-%m-%d %H:%M:" )
apr22$ended_at <- as.POSIXct(apr22$ended_at, format = "%Y-%m-%d %H:%M:" )
may22$started_at <- as.POSIXct(may22$started_at, format = "%Y-%m-%d %H:%M:" )
may22$ended_at <- as.POSIXct(may22$ended_at, format = "%Y-%m-%d %H:%M:" )
jun22$started_at <- as.POSIXct(jun22$started_at, format = "%Y-%m-%d %H:%M:" )
jun22$ended_at <- as.POSIXct(jun22$ended_at, format = "%Y-%m-%d %H:%M:" )
jul22$started_at <- as.POSIXct(jul22$started_at, format = "%Y-%m-%d %H:%M:" )
jul22$ended_at <- as.POSIXct(jul22$ended_at, format = "%Y-%m-%d %H:%M:" )
aug22$started_at <- as.POSIXct(aug22$started_at, format = "%Y-%m-%d %H:%M:" )
aug22$ended_at <- as.POSIXct(aug22$ended_at, format = "%Y-%m-%d %H:%M:" )
sep22$started_at <- as.POSIXct(sep22$started_at, format = "%Y-%m-%d %H:%M:" )
sep22$ended_at <- as.POSIXct(sep22$ended_at, format = "%Y-%m-%d %H:%M:" )
oct22$started_at <- as.POSIXct(oct22$started_at, format = "%Y-%m-%d %H:%M:" )
oct22$ended_at <- as.POSIXct(oct22$ended_at, format = "%Y-%m-%d %H:%M:" )
nov22$started_at <- as.POSIXct(nov22$started_at, format = "%Y-%m-%d %H:%M:" )
nov22$ended_at <- as.POSIXct(nov22$ended_at, format = "%Y-%m-%d %H:%M:" )

Glimpse through the dataset

To ensure that all is the way I want it to be

glimpse(jan22)
glimpse(feb22)
glimpse(mar22)
glimpse(apr22)
glimpse(may22)
glimpse(jun22)
glimpse(jul22)
glimpse(aug22)
glimpse(sep22)
glimpse(oct22)
glimpse(nov22)
glimpse(dec22)

STEP 2: STACK ALL THE DATA SETS and view it

#stack all dataframe

merged_df <- bind_rows(jan22,feb22,mar22,apr22,may22,jun22,jul22,aug22,sep22,oct22,nov22,dec22)

glimpse(merged_df)

Drop unwanted columns

I forgot to mention that I tried doing all these in excel before now, but couldn’t because of the large datasets. I already created some columns in some specific months which I currently do not need so I have to drop them

merged_df <- merged_df %>% 
  select(-c(ride_length, day_of_week, day_of_the_week, Descriptive_analysis, X))

Change the datatype of ride_id

merged_df <- merged_df %>% 
  mutate(ride_id = as.character(ride_id), rideable_type = as.character(rideable_type))

STEP 3: CLEAN UP AND ADD DATA TO PREPARE FOR ANALYSIS

The data can only be aggregated at the ride-level, which is too granular. We will want to add some additional columns of data – such as date, day, month, year, day of week – that provide additional opportunities to aggregate the data. We will want to add a calculated field for length of ride since the 2022 data did not have the “tripduration” column. We will add “ride_length” to the entire dataframe for consistency. *There are some rides where tripduration shows up as negative, including several hundred rides where Divvy took bikes out of circulation for Quality Control reasons. We will want to delete these rides.

Add columns that shows the day, month, week , year of each ride

merged_df$date <- as.Date(merged_df$started_at) #The default format is yyyy-mm-dd
merged_df$month <- format(as.Date(merged_df$date), "%m")
merged_df$day <- format(as.Date(merged_df$date), "%d")
merged_df$year <- format(as.Date(merged_df$date), "%Y")
merged_df$day_of_week <- format(as.Date(merged_df$date), "%A")

Adding ride length calculations using time difference

Using the base function difftime, we calculate the difference between two date-time objects. In this case, started_at and ended_at

merged_df$ride_length <- difftime(merged_df$ended_at,merged_df$started_at)

Inspect the structure of the columns

str(merged_df)

Convert “ride_length”

From Factor to numeric so we can run calculations on the data

is.factor(merged_df$ride_length)
merged_df$ride_length <- as.numeric(as.character(merged_df$ride_length))
is.numeric(merged_df$ride_length)

Remove “bad” data

The dataframe includes a few hundred entries when bikes were taken out of docks and checked for quality by Divvy or ride_length was negative We will create a new version of the dataframe (v2) since data is being removed ### https://www.datasciencemadesimple.com/delete-or-drop-rows-in-r-with-conditions-2/

merged_df_v2 <- merged_df[!(merged_df$start_station_name == "HQ QR" |merged_df$ride_length<=0),]

STEP 4: CONDUCT DESCRIPTIVE ANALYSIS

Descriptive analysis on ride_length (all figures in seconds)

mean(merged_df_v2$ride_length, na.rm=TRUE) #straight average (total ride length / rides)
median(merged_df_v2$ride_length, na.rm = TRUE) #midpoint number in the ascending array of ride lengths
max(merged_df_v2$ride_length,  na.rm = TRUE) #longest ride
min(merged_df_v2$ride_length,  na.rm = TRUE) #shortest ride

See the average ride time by each day for members vs casual users

The aggregate function helps to summarize datasets by creating subsets based on certain conditions. The FUN = mean specifies that the particular function to be applied to each subset of data is the mean() function

aggregate(merged_df_v2$ride_length ~ merged_df_v2$member_casual + merged_df_v2$day_of_week, FUN = mean)

Notice that the days of the week are out of order.

Let’s fix that using the ordered function and specifying the levels as a list and run the code again.

merged_df_v2$day_of_week <- ordered(merged_df_v2$day_of_week, levels=c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))
aggregate(merged_df_v2$ride_length ~ merged_df_v2$member_casual + merged_df_v2$day_of_week, FUN = mean)

Analyze ridership data by type and weekday and export

ridership <- 
  merged_df_v2 %>% 
  mutate(weekday = wday(started_at, label = TRUE)) %>%  #creates weekday field using wday()
  group_by(member_casual, weekday) %>%  #groups by usertype and weekday
  summarise(number_of_rides = n()                           #calculates the number of rides and average duration 
            ,average_duration = mean(ride_length)) %>%      # calculates the average duration
  arrange(member_casual, weekday)                               # sorts

#export ridership as a csv file for vizualisation
write.csv(ridership, file = "C:/Users/Admin/Documents/data_projects/cyclistic_2022/ridership.csv")

Let’s visualize the number of rides by rider type

  • mutate() function will add a new column called weekday and wday specifies that each entry is the weekday of the corresponding date in started_at column. The label=TRUE part makes it return the actual day names.
  • group_by is used to group the data based on the variables specified
  • summarise will create a new data frame. number_of_rides = n() will counts the total number of rides and average_duration calculates the average ride length
  • arrange is used to sort in ascending or descending order.
  • ggplot will create a chart, aes is used to specify that the x and y axis will be weekday and average_duration respectively while fill=member_casual will colour it based on the member_casual column
  • geom_col is a function in ggplot2 used to create bar charts. position = “dodge” is used to make the bars of a bar chart sit side-by-side instead of stacking
merged_df_v2 %>% 
  mutate(weekday = wday(started_at, label = TRUE)) %>% 
  group_by(member_casual, weekday) %>% 
  summarise(number_of_rides = n()
            ,average_duration = mean(ride_length)) %>% 
  arrange(member_casual, weekday)  %>% 
  ggplot(aes(x = weekday, y = number_of_rides, fill = member_casual)) +
  geom_col(position = "dodge")

Let’s create a visualization for average duration

merged_df_v2 %>% 
  mutate(weekday = wday(started_at, label = TRUE)) %>% 
  group_by(member_casual, weekday) %>% 
  summarise(number_of_rides = n()
            ,average_duration = mean(ride_length)) %>% 
  arrange(member_casual, weekday)  %>% 
  ggplot(aes(x = weekday, y = average_duration, fill = member_casual)) +
  geom_col(position = "dodge")