R Markdown Document

Cyclistic Bikesharing Casestudy

How Does a Bike-Share Navigate Speedy Success?

Introduction

This project is a reference from a publically available dataset for Google Data Analytic Certificate course through Coursera. I have used this case study for my R-Project. In this Project, I am using a data set of 6 months for different bike-rides for a fictitious Cyclistic Company. The goal of the project is to study how the casual riders and annual members use the bikes. Further, the study entails to find out ways to a research question as to how can the casual riders be converted to annual members.

Data used

I will be using Cyclistic’s historical trip data to analyze and identify trends. The data is provided on this link (Click to Open). (Note: The datasets have a different names because Cyclistic is a fictional company. The data has been made available by Motivate International Inc. under this license.) I choose to work with the data of 6 months of recent year (June 2023 to November 2023).

The data is provided by the bike-sharing company, Lyft Bikes and Scooters, LLC and City of Chicago. The datasets includes data about the bike rides of the company. It includes the number of rides, the type of bikes used, starting and end times of the rides, and the stations where the rides began from and where they ended, and finally it also includes the user details whether the user is a member or a casual rider. Since the data is a primary dataset provide by the company itself, there are no normalization issues in the dataset and the information is provided for every month and it covers details of all the trips. Further, the data fulfils the criteria for being ROCCC, i.e. Reliable and Original (as it is the primary data downloaded from the company website), Comprehensive (all the details are present), current (the data is periodically updated every month), and cited.

Further, the data is used within the boundaries established in the Data License Agreement.

The given dataset has the following columns/ data fields -

"ride_id"
"rideable_type"
"started_at" 
"ended_at"
"start_station_name"
"start_station_id"
"end_station_name"
"end_station_id"
"start_lat" 
"start_lng" 
"end_lat"  
"end_lng" 
"member_casual"     

Methodology

First, I have collected the data and have a look at the available data set. I looked at the different column values, the data types, and also the fields available in the data set. Further, I move ahead with data cleaning and normalization. Below are the initial steps, where I have cleaned the data, changed the data types (date-time values), used data-transformation and also filtered out the outliers. After the data cleaning and standardization, I get a combined and cleaned data frame.

Then I Moved ahead to create visualization to see how the bike usage varies between the members and the casual riders. I checked for the total spread of the two types of users, the spread as per different bike types, bike usage at different time of day, average bike ride durations, bike usage trend on weekly basis, most frequent pickup and drop off points for both casual and member riders, and then specifically for casual riders. In analysis, I have used simple statistical measures Mean (for average ride times) and Mode (most pikup and drop off location). I also used histogram plots to check the time slot of the day at which most bike rides are taken, and also for the weekly analysis of data to see the trends in bike usage.

After analyzing this data, I have summarized my findings.

# Importing Important Packages that will be useful later.

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.2
## 
## 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)
## Warning: package 'ggplot2' was built under R version 4.3.2
library(stringr)
## Warning: package 'stringr' was built under R version 4.3.2
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.2
## Warning: package 'tibble' was built under R version 4.3.2
## Warning: package 'tidyr' was built under R version 4.3.2
## Warning: package 'readr' was built under R version 4.3.2
## Warning: package 'purrr' was built under R version 4.3.2
## Warning: package 'forcats' was built under R version 4.3.2
## Warning: package 'lubridate' was built under R version 4.3.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.4
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── 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(plotly)
## Warning: package 'plotly' was built under R version 4.3.2
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.3.2
library(flexdashboard)
## Warning: package 'flexdashboard' was built under R version 4.3.2
# Step 1 : We will Import and Club the data in a single dataframe, but before that, lets have a look at the column names in different files.

jun23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202306-divvy-tripdata.csv")
jul23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202307-divvy-tripdata.csv")
aug23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202308-divvy-tripdata.csv")
sep23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202309-divvy-tripdata.csv")
oct23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202310-divvy-tripdata.csv")
nov23 <- read.csv("C:/Users/Akash Mittal/Documents/R/Capstone/data/202311-divvy-tripdata.csv")

# Lets print the colnames for each month to have a brief look 

colnames(jun23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
colnames(jul23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
colnames(aug23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
colnames(sep23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
colnames(oct23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
colnames(nov23)
##  [1] "ride_id"            "rideable_type"      "started_at"        
##  [4] "ended_at"           "start_station_name" "start_station_id"  
##  [7] "end_station_name"   "end_station_id"     "start_lat"         
## [10] "start_lng"          "end_lat"            "end_lng"           
## [13] "member_casual"
# Let's create a list of data frames for each month
months_list <- list(jun23, jul23, aug23, sep23, oct23, nov23)

# Writing a function to check if column names are the same for multiple data frames
compare_df_cols <- function(dfs) {
  all(sapply(2:length(dfs), function(i) setequal(names(dfs[[i - 1]]), names(dfs[[i]]))))
}

# Let's check if column names are the same for all data frames
columns_same <- compare_df_cols(months_list)
# Printing the result
print(columns_same)
## [1] TRUE
# Now lets combine all the data into a single data frame using bind_rows
combined_data <- bind_rows(months_list)

Let’s Print the Combined DataFrame and have a look at the dataset.

# Print the structure of the combined data frame
str(combined_data)
## 'data.frame':    3824963 obs. of  13 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : chr  "2023-06-05 13:34:12" "2023-06-05 01:30:22" "2023-06-20 18:15:49" "2023-06-19 14:56:00" ...
##  $ ended_at          : chr  "2023-06-05 14:31:56" "2023-06-05 01:33:06" "2023-06-20 18:32:05" "2023-06-19 15:00:35" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
# View the first few rows of the combined data frame
head(combined_data)
##            ride_id rideable_type          started_at            ended_at
## 1 6F1682AC40EB6F71 electric_bike 2023-06-05 13:34:12 2023-06-05 14:31:56
## 2 622A1686D64948EB electric_bike 2023-06-05 01:30:22 2023-06-05 01:33:06
## 3 3C88859D926253B4 electric_bike 2023-06-20 18:15:49 2023-06-20 18:32:05
## 4 EAD8A5E0259DEC88 electric_bike 2023-06-19 14:56:00 2023-06-19 15:00:35
## 5 5A36F21930D6A55C electric_bike 2023-06-19 15:03:34 2023-06-19 15:07:16
## 6 CF682EA7D0F961DB electric_bike 2023-06-09 21:30:25 2023-06-09 21:49:52
##   start_station_name start_station_id end_station_name end_station_id start_lat
## 1                                                                         41.91
## 2                                                                         41.94
## 3                                                                         41.95
## 4                                                                         41.99
## 5                                                                         41.98
## 6                                                                         41.99
##   start_lng end_lat end_lng member_casual
## 1    -87.69   41.91  -87.70        member
## 2    -87.65   41.94  -87.65        member
## 3    -87.68   41.92  -87.63        member
## 4    -87.65   41.98  -87.66        member
## 5    -87.66   41.99  -87.65        member
## 6    -87.68   41.94  -87.65        member

We see that “started_at” and “ended_at” Columns are formatted as character datatype, let’s reformat them to Date-Time, using the”lubridate” package.

library(lubridate)

# Let's convert "started_at" and "ended_at" to date-time format

combined_data$started_at <- ymd_hms(combined_data$started_at)
combined_data$ended_at <- ymd_hms(combined_data$ended_at)

# Let's also calculate the ride duration and add a column for the ride_duration by calculating the difference between the star and end times and considering the units as "minutes".

combined_data$ride_duration <- difftime(combined_data$ended_at, combined_data$started_at, units = "mins")

# Let's have a look at the structure of our updated data frame
str(combined_data)
## 'data.frame':    3824963 obs. of  14 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : POSIXct, format: "2023-06-05 13:34:12" "2023-06-05 01:30:22" ...
##  $ ended_at          : POSIXct, format: "2023-06-05 14:31:56" "2023-06-05 01:33:06" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
##  $ ride_duration     : 'difftime' num  57.7333333333333 2.73333333333333 16.2666666666667 4.58333333333333 ...
##   ..- attr(*, "units")= chr "mins"

Let’s analyze the ride-duration for data consistency and accuracy. There should not be any negative ride duration, if there are any, I am skipping those rows from the analysis and filter the data accordingly. Further, I am also skipping the data for any rides of less than 2 minutes and greater than 1440 minutes (i.e. 24 hrs) to remove outliers.

Note: I have personally checked that there are outliers for ride durations with fewer rows and a very large ride duration for weeks or so. I have considered a maximum ride duration in single go, for a day, i.e. 24 hrs (1440 minutes) for the analysis. Thus, I have dropped the outliers.

# Lets check the minimum and maximum ride durations

min_ride_duration <- min(combined_data$ride_duration)
max_ride_duration <- max(combined_data$ride_duration)

# Print the results
cat("Minimum Ride Duration:", min_ride_duration, "minutes\n")
## Minimum Ride Duration: -16656.52 minutes
cat("Maximum Ride Duration:", max_ride_duration, "minutes\n")
## Maximum Ride Duration: 98489.07 minutes
# Since there are also negative ride times which cannot be true, and also the ride times less than 2 minutes, lets normalize data to drop rows with negative ride time.
# Lets also drop ride times greater than and equal to 1440 minutes.
filtered_data <- combined_data %>%
  filter(ride_duration >= 2 & ride_duration <= 1440)

# View the structure of the filtered data frame
str(filtered_data)
## 'data.frame':    3659282 obs. of  14 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : POSIXct, format: "2023-06-05 13:34:12" "2023-06-05 01:30:22" ...
##  $ ended_at          : POSIXct, format: "2023-06-05 14:31:56" "2023-06-05 01:33:06" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
##  $ ride_duration     : 'difftime' num  57.7333333333333 2.73333333333333 16.2666666666667 4.58333333333333 ...
##   ..- attr(*, "units")= chr "mins"

Let’s have a look at the top 10 Ride Duration to see the maximum ride times.

# # Find the top 10 ride durations
sorted_data <- filtered_data %>%
  arrange(desc(ride_duration))

# Selecting the top 10 rides with the maximum ride durations
top_10_max_rides <- head(sorted_data, 10)

# Printing the details of the top 10 rides with maximum durations
print(top_10_max_rides)
##             ride_id rideable_type          started_at            ended_at
## 1  E909A50921F16CB2  classic_bike 2023-11-05 00:40:17 2023-11-06 00:40:12
## 2  8E01CDDA5B3F24FB  classic_bike 2023-11-04 21:31:45 2023-11-05 21:31:40
## 3  47B35ED4AB9309D6  classic_bike 2023-11-04 04:23:59 2023-11-05 04:23:54
## 4  F5AB6DA725B1864F  classic_bike 2023-11-04 20:53:10 2023-11-05 20:53:05
## 5  4FACA5E6A6D0854B  classic_bike 2023-11-04 09:59:47 2023-11-05 09:59:41
## 6  F0D6F077D7C8BADA  classic_bike 2023-11-04 09:54:36 2023-11-05 09:54:30
## 7  92D979D502AE0573  classic_bike 2023-11-04 09:56:46 2023-11-05 09:56:40
## 8  BD7095FDB00EF5A9  classic_bike 2023-11-04 23:25:31 2023-11-05 23:25:25
## 9  1DB71E2F45F4E568  classic_bike 2023-11-04 09:55:04 2023-11-05 09:54:58
## 10 48BBB787A709BEB8  classic_bike 2023-11-04 18:06:00 2023-11-05 18:05:54
##                         start_station_name start_station_id end_station_name
## 1                     Rhodes Ave & 32nd St            13215                 
## 2            Sheffield Ave & Fullerton Ave     TA1306000016                 
## 3  Wolcott (Ravenswood) Ave & Montrose Ave     TA1307000144                 
## 4           Sheffield Ave & Wrightwood Ave     TA1309000023                 
## 5           Sheffield Ave & Wellington Ave     TA1307000052                 
## 6           Sheffield Ave & Wellington Ave     TA1307000052                 
## 7           Sheffield Ave & Wellington Ave     TA1307000052                 
## 8              Lincoln Ave & Fullerton Ave     TA1309000058                 
## 9               Indiana Ave & Roosevelt Rd           SL-005                 
## 10                     Clark St & Grace St     TA1307000127                 
##    end_station_id start_lat start_lng end_lat end_lng member_casual
## 1                  41.83621 -87.61353      NA      NA        member
## 2                  41.92560 -87.65371      NA      NA        member
## 3                  41.96141 -87.67617      NA      NA        casual
## 4                  41.92871 -87.65383      NA      NA        casual
## 5                  41.93625 -87.65266      NA      NA        casual
## 6                  41.93625 -87.65266      NA      NA        casual
## 7                  41.93625 -87.65266      NA      NA        casual
## 8                  41.92416 -87.64638      NA      NA        member
## 9                  41.86789 -87.62304      NA      NA        member
## 10                 41.95078 -87.65917      NA      NA        casual
##    ride_duration
## 1  1439.917 mins
## 2  1439.917 mins
## 3  1439.917 mins
## 4  1439.917 mins
## 5  1439.900 mins
## 6  1439.900 mins
## 7  1439.900 mins
## 8  1439.900 mins
## 9  1439.900 mins
## 10 1439.900 mins

Now let’s have a look at the rideable_type field and the values present in it -

unique_rideable_types <- unique(filtered_data$rideable_type)

# Print the unique rideable types
print(unique_rideable_types)
## [1] "electric_bike" "classic_bike"  "docked_bike"

So we get 3 bike types in output, eletrcic_bike, classic_bike and docked_bike. This seems good and as per the required data.

For a quick lookup, let’s also check the user type in the dataset -

user_types <- unique(filtered_data$member_casual)

# Print the unique rideable types
print(user_types)
## [1] "member" "casual"

As expected the values are only member and casual, so this data is also good.

Note: I have initially checked there is no Null value in data for User types, or Bike Types, started_at etc. but there are null values in Location Parameters, so lets have a loot at them and normalize the data.

# Check for null values in specified columns, start_lat, start_lng, end_lat, and end_lng
columns_to_check <- c("start_lat", "start_lng", "end_lat", "end_lng")

null_values_summary <- filtered_data %>%
  select(all_of(columns_to_check)) %>%
  summarise_all(~sum(is.na(.)))

# Print the summary
print(null_values_summary)
##   start_lat start_lng end_lat end_lng
## 1         0         0     507     507

So there are 507 fields with missing values for end location of the ride. As this is quite a less amount of missing data, we will drop this from our analysis and filter the data.

But first there is a question, if there is any row where “end_lat” is missing, but “end_lng” is present and vice versa. Lets check that for data consistency

# Check for rows with inconsistent missing values in end_lat and end_lng

inconsistent_end_location_data <- filtered_data %>% filter((is.na(end_lat) & !is.na(end_lng)) | (!is.na(end_lat) & is.na(end_lng)))

# Print the inconsistent rows

print(inconsistent_end_location_data)
##  [1] ride_id            rideable_type      started_at         ended_at          
##  [5] start_station_name start_station_id   end_station_name   end_station_id    
##  [9] start_lat          start_lng          end_lat            end_lng           
## [13] member_casual      ride_duration     
## <0 rows> (or 0-length row.names)

So, the missing values are in pair, that is good. Let’s drop this missing data from the analysis as it is only few rows.

filtered_data <- filtered_data %>%
  dplyr::filter(!is.na(end_lat) & !is.na(end_lng))
# Print the structure of the combined data frame
str(filtered_data)
## 'data.frame':    3658775 obs. of  14 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : POSIXct, format: "2023-06-05 13:34:12" "2023-06-05 01:30:22" ...
##  $ ended_at          : POSIXct, format: "2023-06-05 14:31:56" "2023-06-05 01:33:06" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
##  $ ride_duration     : 'difftime' num  57.7333333333333 2.73333333333333 16.2666666666667 4.58333333333333 ...
##   ..- attr(*, "units")= chr "mins"
# View the first few rows of the combined data frame
head(filtered_data)
##            ride_id rideable_type          started_at            ended_at
## 1 6F1682AC40EB6F71 electric_bike 2023-06-05 13:34:12 2023-06-05 14:31:56
## 2 622A1686D64948EB electric_bike 2023-06-05 01:30:22 2023-06-05 01:33:06
## 3 3C88859D926253B4 electric_bike 2023-06-20 18:15:49 2023-06-20 18:32:05
## 4 EAD8A5E0259DEC88 electric_bike 2023-06-19 14:56:00 2023-06-19 15:00:35
## 5 5A36F21930D6A55C electric_bike 2023-06-19 15:03:34 2023-06-19 15:07:16
## 6 CF682EA7D0F961DB electric_bike 2023-06-09 21:30:25 2023-06-09 21:49:52
##   start_station_name start_station_id end_station_name end_station_id start_lat
## 1                                                                         41.91
## 2                                                                         41.94
## 3                                                                         41.95
## 4                                                                         41.99
## 5                                                                         41.98
## 6                                                                         41.99
##   start_lng end_lat end_lng member_casual  ride_duration
## 1    -87.69   41.91  -87.70        member 57.733333 mins
## 2    -87.65   41.94  -87.65        member  2.733333 mins
## 3    -87.68   41.92  -87.63        member 16.266667 mins
## 4    -87.65   41.98  -87.66        member  4.583333 mins
## 5    -87.66   41.99  -87.65        member  3.700000 mins
## 6    -87.68   41.94  -87.65        member 19.450000 mins

Now Let’s quickly check the dimension of the data also.

dim(filtered_data)
## [1] 3658775      14

So there are 3658775 Rows and 14 Columns. Now let’s also find out days of week for the start and end days of rides -

#Add a new column for the day of the week for both start of ride and end of ride

filtered_data$day_of_week_start <- wday(filtered_data$started_at, label = TRUE)
filtered_data$day_of_week_end <- wday(filtered_data$ended_at, label = TRUE)

# Print the updated data frame just head 
head(filtered_data)
##            ride_id rideable_type          started_at            ended_at
## 1 6F1682AC40EB6F71 electric_bike 2023-06-05 13:34:12 2023-06-05 14:31:56
## 2 622A1686D64948EB electric_bike 2023-06-05 01:30:22 2023-06-05 01:33:06
## 3 3C88859D926253B4 electric_bike 2023-06-20 18:15:49 2023-06-20 18:32:05
## 4 EAD8A5E0259DEC88 electric_bike 2023-06-19 14:56:00 2023-06-19 15:00:35
## 5 5A36F21930D6A55C electric_bike 2023-06-19 15:03:34 2023-06-19 15:07:16
## 6 CF682EA7D0F961DB electric_bike 2023-06-09 21:30:25 2023-06-09 21:49:52
##   start_station_name start_station_id end_station_name end_station_id start_lat
## 1                                                                         41.91
## 2                                                                         41.94
## 3                                                                         41.95
## 4                                                                         41.99
## 5                                                                         41.98
## 6                                                                         41.99
##   start_lng end_lat end_lng member_casual  ride_duration day_of_week_start
## 1    -87.69   41.91  -87.70        member 57.733333 mins               Mon
## 2    -87.65   41.94  -87.65        member  2.733333 mins               Mon
## 3    -87.68   41.92  -87.63        member 16.266667 mins               Tue
## 4    -87.65   41.98  -87.66        member  4.583333 mins               Mon
## 5    -87.66   41.99  -87.65        member  3.700000 mins               Mon
## 6    -87.68   41.94  -87.65        member 19.450000 mins               Fri
##   day_of_week_end
## 1             Mon
## 2             Mon
## 3             Tue
## 4             Mon
## 5             Mon
## 6             Fri
# Lets have a look at the structure of the dataset
str(filtered_data)
## 'data.frame':    3658775 obs. of  16 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : POSIXct, format: "2023-06-05 13:34:12" "2023-06-05 01:30:22" ...
##  $ ended_at          : POSIXct, format: "2023-06-05 14:31:56" "2023-06-05 01:33:06" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
##  $ ride_duration     : 'difftime' num  57.7333333333333 2.73333333333333 16.2666666666667 4.58333333333333 ...
##   ..- attr(*, "units")= chr "mins"
##  $ day_of_week_start : Ord.factor w/ 7 levels "Sun"<"Mon"<"Tue"<..: 2 2 3 2 2 6 6 6 6 6 ...
##  $ day_of_week_end   : Ord.factor w/ 7 levels "Sun"<"Mon"<"Tue"<..: 2 2 3 2 2 6 6 7 6 6 ...
# Lets also check for any duplicate ride ids in the ride_id column for data integrity.
duplicate_ride_ids <- filtered_data %>%
  filter(duplicated(ride_id) | duplicated(ride_id, fromLast = TRUE))

# Print the rows with duplicate ride_id values
x <- count(duplicate_ride_ids)
print(x$count)
## NULL

Wow, so there are no duplicate values in the ride_id. This is great.

#Simple Codechunk to check the duplicates

any(duplicated(filtered_data$ride_id))
## [1] FALSE

Great, We see from both the methods, the output is No Duplicate Values. So now, let’s proceed with our analysis.

Results, Visualizations and Plots for Analysis

Plot 1 - Count of Rides by each type of riders

Let’s Check the count of rides taken by members and the casual riders. For this, let’s plot a bar-graph using ggplot2.

# Count of Rides by each type of riders. Let's group the data by member_casual column.

count_percentage_data <- filtered_data %>%
  group_by(member_casual) %>%
  summarise(count = n()) %>%
  mutate(percentage = count / sum(count) * 100)


count_percentage_data
## # A tibble: 2 × 3
##   member_casual   count percentage
##   <chr>           <int>      <dbl>
## 1 casual        1419170       38.8
## 2 member        2239605       61.2

Let’s Plot this data using ggplot2

ggplot(filtered_data, aes(x = member_casual, fill = member_casual)) +
  geom_bar(stat = "count") +
  geom_text(data = count_percentage_data, aes(label = paste(count, " (", round(percentage, 2), "%)"), y = count, group = member_casual), vjust = -0.5) +
  labs(title = "Count and Percentage of Members and Casual Riders", x = "User Type", y = "Count") +
  scale_fill_manual(values = c("member" = "lightblue", "casual" = "pink")) +
  theme_minimal()

From the graph, we see that of all the rides, 38.79% rides are taken by casual riders, and 61.21% are taken by members.

Plot 2 - Count of Rides by ride type

Now, lets plot the rides count by the type of Bikes also, to see, how these users are using the different types of bikes. We can do this using the facet_wrap function of ggplot2.

#Count and percentage Table for data
count_percentage_data <- filtered_data %>%
  group_by(member_casual, rideable_type) %>%
  summarise(count = n(), .groups = 'drop') %>%
  mutate(percentage = count / sum(count) * 100)

count_percentage_data
## # A tibble: 5 × 4
##   member_casual rideable_type   count percentage
##   <chr>         <chr>           <int>      <dbl>
## 1 casual        classic_bike   646964      17.7 
## 2 casual        docked_bike     47164       1.29
## 3 casual        electric_bike  725042      19.8 
## 4 member        classic_bike  1156257      31.6 
## 5 member        electric_bike 1083348      29.6
# Plotting the curve.

ggplot(count_percentage_data, aes(x = member_casual, y = count, fill = member_casual)) +
  geom_bar(stat = "identity", position = "stack") +
  geom_text(aes(label = paste0(" (", round(percentage, 2), "%)")), 
            position = position_stack(vjust = 0.5),
            size = 3, 
            stat = "identity") +  # Specifying stat = "identity" for proper positioning
  labs(title = "Percentage Count of Members and Casual Riders For Each Bike Type", x = "User Type", y = "Count") +
  scale_fill_manual(values = c("member" = "lightblue", "casual" = "pink")) +
  facet_wrap(~rideable_type) +
  theme_minimal()

From this data, we see that the “Docked Bikes” are least used bikes by casual riders (~3%) as well as members (~0%).

Plot 3 - Bike Type Distribution by Rider (User) Type

Let’s also compare this data in a more convenient way as follows -

# Create a stacked bar plot
bike_type_plot <- ggplot(count_percentage_data, aes(x = member_casual, y = percentage, fill = rideable_type)) +
  geom_bar(stat = "identity", position = "stack", width = 0.7) +
  geom_text(aes(label = paste0(" (", round(percentage, 2), "%)")),
            position = position_stack(vjust = 0.5),
            size = 3) +
  labs(title = "Bike Type Distribution by Rider Type", x = "Rider Type", y = "Percentage", fill = "Bike Type") +
  scale_fill_manual(values = c("electric_bike" = "orange3", "classic_bike" = "cyan2", "docked_bike" = "plum3")) +
  theme_minimal()

# Display the plot
print(bike_type_plot)

# Creating a summary dataset for bike type counts
bike_type_counts <- filtered_data %>%
  group_by(member_casual, rideable_type) %>%
  summarise(count = n(), .groups = 'drop') %>%
  mutate(percentage = count / sum(count) * 100)

bike_type_counts
## # A tibble: 5 × 4
##   member_casual rideable_type   count percentage
##   <chr>         <chr>           <int>      <dbl>
## 1 casual        classic_bike   646964      17.7 
## 2 casual        docked_bike     47164       1.29
## 3 casual        electric_bike  725042      19.8 
## 4 member        classic_bike  1156257      31.6 
## 5 member        electric_bike 1083348      29.6

Plot 4 - Ride Time (average) Duration vs User Type

Now, let’s check the ride time duration as per different rider types.

# Calculating the average ride time for each user type

average_ride_time <- filtered_data %>%
  group_by(member_casual) %>%
  summarise(average_time = mean(ride_duration, na.rm = TRUE))

# Plotting the average ride time with text labels
ggplot(average_ride_time, aes(x = member_casual, y = as.numeric(average_time), fill = member_casual)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = paste(round(average_time, 2), " mins"), y = average_time),
            position = position_dodge(width = 0.9),
            vjust = -0.5) +
  labs(
    title = "Average Ride Time by User Type",
    x = "User Type",
    y = "Average Ride Time (minutes)"
  ) +
  scale_fill_manual(values = c("member" = "lightblue", "casual" = "pink")) +
  theme_minimal()+
  theme(
    plot.title = element_text(hjust = 0.5) # To center the Plot Title
  )

The data is interesting, as it shows the average ride time for Casual Riders is almost ~8 Minutes more than that of members.

Findings till Now -> There are only 38% Casual Riders, and the rest 61% are Annual Members. Further, the Casual riders have a higher average ride time than the members. Additionally, the docked_bikes are the least used by any type of user.

Plot 5 - Ride Counts by day time and User Type

Now, lets see when do the riders generally use the bikes. For this lets plot the start_day and count of rides on different days of week for both, the Casual Riders as well as Members.

# Factoring the dataset for weekdays.
filtered_data$start_day <- factor(
  format(filtered_data$started_at, "%A"),
  levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
  ordered = TRUE
)

# Creating a summary dataset for ride counts by day and user type
ride_day_counts <- filtered_data %>%
  group_by(member_casual, start_day) %>%
  summarise(count = n(), .groups = 'drop')

# Plotting the ride counts by day and user type
ggplot(ride_day_counts, aes(x = start_day, y = count, fill = member_casual)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(
    title = "Ride Counts by Day and User Type",
    x = "Day of Week",
    y = "Count"
  ) +
  scale_fill_manual(values = c("member" = "lightblue", "casual" = "pink")) +
  theme_minimal()

A quick look at the graph brings out the following insights ->

  • members are using more bikes on weekdays, and

  • the casual riders are using the more bikes on weekends.

This analysis seems justifiable as the members might commute to work on weekdays, and there would be more people casually riding the bikes on weekends for leisure activities.

Plot 6 - Ride Count by Time of Day

Let’s also plot different times of day when the bikes are taken, by each of the different riders.

library(hms)
## Warning: package 'hms' was built under R version 4.3.2
## 
## Attaching package: 'hms'
## The following object is masked from 'package:lubridate':
## 
##     hms
filtered_data$starting_time <- as_hms(format(as.POSIXct(filtered_data$started_at, format="%Y-%m-%d %H:%M:%S"), "%H:%M:%S"))

# Check the structure of your data frame
str(filtered_data)
## 'data.frame':    3658775 obs. of  18 variables:
##  $ ride_id           : chr  "6F1682AC40EB6F71" "622A1686D64948EB" "3C88859D926253B4" "EAD8A5E0259DEC88" ...
##  $ rideable_type     : chr  "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ started_at        : POSIXct, format: "2023-06-05 13:34:12" "2023-06-05 01:30:22" ...
##  $ ended_at          : POSIXct, format: "2023-06-05 14:31:56" "2023-06-05 01:33:06" ...
##  $ start_station_name: chr  "" "" "" "" ...
##  $ start_station_id  : chr  "" "" "" "" ...
##  $ end_station_name  : chr  "" "" "" "" ...
##  $ end_station_id    : chr  "" "" "" "" ...
##  $ start_lat         : num  41.9 41.9 42 42 42 ...
##  $ start_lng         : num  -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat           : num  41.9 41.9 41.9 42 42 ...
##  $ end_lng           : num  -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ member_casual     : chr  "member" "member" "member" "member" ...
##  $ ride_duration     : 'difftime' num  57.7333333333333 2.73333333333333 16.2666666666667 4.58333333333333 ...
##   ..- attr(*, "units")= chr "mins"
##  $ day_of_week_start : Ord.factor w/ 7 levels "Sun"<"Mon"<"Tue"<..: 2 2 3 2 2 6 6 6 6 6 ...
##  $ day_of_week_end   : Ord.factor w/ 7 levels "Sun"<"Mon"<"Tue"<..: 2 2 3 2 2 6 6 7 6 6 ...
##  $ start_day         : Ord.factor w/ 7 levels "Monday"<"Tuesday"<..: 1 1 2 1 1 5 5 5 5 5 ...
##  $ starting_time     : 'hms' num  13:34:12 01:30:22 18:15:49 14:56:00 ...
##   ..- attr(*, "units")= chr "secs"
# Convert the starting_time column to POSIXct class
filtered_data$starting_time <- as.POSIXct(filtered_data$starting_time, format = "%H:%M:%S")

# Extracting the hour from the starting_time
filtered_data$hour <- format(filtered_data$starting_time, "%H")

# Grouping and summarizing the data
time_counts <- filtered_data %>%
  group_by(member_casual, hour) %>%
  summarise(count = n(), .groups = 'drop')

# Plotting the graph
ggplot(time_counts, aes(x = hour, y = count, fill = member_casual)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Rides Count by Time of Day",
       x = "Hour of Day",
       y = "Ride Count") +
  scale_fill_manual(values = c("member" = "lightblue", "casual" = "pink")) +
  theme_minimal()

Findings from this graph are interesting -

1. It shows that the members use the bikes mostly during the Morning Time (7-9 am, i.e. Morning times for office hour or students possibly for travelling to school or University.)

2. Similarly, there is a peak in bike usage by members in the evening peak hours, (4-6 pm), which corresponding to closing times for Universities and Officies also. This indicates that the a significant amount of members are the working professionals or students.

3. The data shows, that there is a significant increase in use of bikes by casual riders in afternoon. This might be the because of leisure activities in the evening.

Plot 7 - Plotting The Top 20 Pickup and Top 20 Drop-Off Locations on Map

Now, let use the longitude and latitude data, to plot the top 20 locations for Bike Pickups, and top 20 locations for Bike Drop (Destinations).

library(leaflet)

cleaned_data <- filtered_data %>%
  filter(
    complete.cases(start_lat, start_lng, end_lat, end_lng)
  )

# Top 20 pickup locations
top_pickup <- cleaned_data %>%
  group_by(start_lat, start_lng, member_casual) %>%
  summarise(count = n(), .groups = 'drop') %>%
  arrange(desc(count)) %>%
  slice_head(n = 20)

# Top 20 drop locations
top_drop <- cleaned_data %>%
  group_by(end_lat, end_lng, member_casual) %>%
  summarise(count = n(), .groups = 'drop') %>%
  arrange(desc(count)) %>%
  slice_head(n = 20)

Let’s Create a Function to add Markers on the Map

add_markers <- function(map, data, color) {
  map <- addCircleMarkers(
    map,
    lng = data$start_lng,
    lat = data$start_lat,
    radius = sqrt(data$count) * 2,
    color = color,
    fillOpacity = 0.7,
    popup = paste("Count: ", data$count),
    label = as.character(data$count)
  )
  return(map)
}

Now Let’s Plot Top Pickup and Drop-Off Locations ->

# Create a leaflet map for top pickup locations
pickup_map <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lng = top_pickup$start_lng,
    lat = top_pickup$start_lat,
    radius = sqrt(top_pickup$count) * 0.05,
    color = "brown",
    fillOpacity = 0.7,
    popup = paste("Count: ", top_pickup$count),
    label = as.character(top_pickup$count)
  )

# Create a leaflet map for top drop locations
drop_map <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lng = top_drop$end_lng,
    lat = top_drop$end_lat,
    radius = sqrt(top_drop$count) * 0.05,
    color = "violetred2",
    fillOpacity = 0.7,
    popup = paste("Count: ", top_drop$count),
    label = as.character(top_drop$count)
  )

# Print the maps
pickup_map
drop_map

In the Map, the locations are shown by small circles. The radius of circle varies as per the count of rides from specific location.

Plot 8 - Filtering and Plotting the top 15 Pickup and top 15 Drop-Off Locations on Map for Casual Riders

Now, Since we need to focus on the Casual Members conversion, let’s check the top 15 Locations that casual riders visit for pickup and drop off of the bikes.

#Filtering and sorting the Data for Casual Riders

# Top 15 pickup locations for casual riders
top_pickup_casual <- cleaned_data %>%
  filter(member_casual == "casual") %>%
  group_by(start_lat, start_lng) %>%
  summarise(count = n(), .groups = 'drop') %>%
  arrange(desc(count)) %>%
  slice_head(n = 20)

# Top 15 drop locations for casual riders
top_drop_casual <- cleaned_data %>%
  filter(member_casual == "casual") %>%
  group_by(end_lat, end_lng) %>%
  summarise(count = n(), .groups = 'drop') %>%
  arrange(desc(count)) %>%
  slice_head(n = 20)
#Plotting the data for Casual Riders

# Create a leaflet map for top pickup locations for casual riders
pickup_map_casual <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lng = top_pickup_casual$start_lng,
    lat = top_pickup_casual$start_lat,
    radius = sqrt(top_pickup_casual$count) * 0.05,
    color = "black",
    fillOpacity = 0.7,
    popup = paste("Count: ", top_pickup_casual$count),
    label = as.character(top_pickup_casual$count)
  )

# Create a leaflet map for top drop locations for casual riders
drop_map_casual <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lng = top_drop_casual$end_lng,
    lat = top_drop_casual$end_lat,
    radius = sqrt(top_drop_casual$count) * 0.05,
    color = "green",
    fillOpacity = 0.7,
    popup = paste("Count: ", top_drop_casual$count),
    label = as.character(top_drop_casual$count)
  )

# Print the maps
pickup_map_casual
drop_map_casual

These Locations do overlap to most extent with overall locations for maximum pick-up and drop-off locations.

Plot 9 - Weekly Trend Data (Part 1 - Stacked Column Chart)

For a Trend check, Let’s also plot weekly ride data for casual and member riders

# Convert "started_at" to a date format if it's not already in that format
filtered_data$started_at <- as.Date(filtered_data$started_at)

# Create a new column for the week number
filtered_data$week_number <- format(filtered_data$started_at, "%U")

# Subtract the minimum week number to start from 1, so that week count starts from 1
filtered_data$week_number <- as.numeric(filtered_data$week_number) - min(as.numeric(filtered_data$week_number)) + 1

# Group by week number and rider type, then calculate the count
weekly_rides <- filtered_data %>%
  group_by(week_number, member_casual) %>%
  summarise(ride_count = n(), .groups = 'drop')

# Plotting the data
library(ggplot2)

ggplot(weekly_rides, aes(x = week_number, y = ride_count, fill = member_casual)) +
  geom_bar(stat = "identity", position = "stack", color = "white") +
  labs(title = "Weekly Ride Data for Casual and Member Riders",
       x = "Week Number",
       y = "Ride Count",
       fill = "Rider Type") +
  theme_minimal()

Plot 10 - Weekly Trend Data (Part 2 - Stacked Percentage Column)

filtered_data$started_at <- as.Date(filtered_data$started_at)

# Create a new column for the week number
filtered_data$week_number <- format(filtered_data$started_at, "%U")

# Subtract the minimum week number to start from 1, so that week count starts from 1
filtered_data$week_number <- as.numeric(filtered_data$week_number) - min(as.numeric(filtered_data$week_number)) + 1

# Group by week number and rider type, then calculate the count
weekly_rides <- filtered_data %>%
  group_by(week_number, member_casual) %>%
  summarise(ride_count = n(), .groups = 'drop')

# Calculate the percentage of each rider type within each week
weekly_rides <- weekly_rides %>%
  group_by(week_number) %>%
  mutate(percentage = ride_count / sum(ride_count) * 100)

# Plotting the data
library(ggplot2)

ggplot(weekly_rides, aes(x = week_number, y = percentage, fill = member_casual)) +
  geom_bar(stat = "identity", position = "fill", color = "white") +
  labs(title = "Weekly Ride Data for Casual and Member Riders",
       x = "Week Number",
       y = "Percentage of Rides",
       fill = "Rider Type") +
  scale_y_continuous(labels = scales::percent_format(scale = 1)) +
  theme_minimal()

From the above two Graphs we see, there is a decrease in overall rides on weekly basis.

One reason could be the Colder Months, which makes it difficult to ride the bikes in Winters. Thus drop in the overall count of members and the casual riders riding the bikes.

Conclusions

By the analysis of above plots and results, I have following conclusions -

  1. Ride Type Analysis:

    • Plot 1: Casual riders contribute to approximately 38.79% of all rides, while members make up the remaining 61.21%. This suggests a substantial user base for potential conversion.

    • Plot 2: “Docked Bikes” are the least used ride type by both casual riders (~3%) and members (~0%).

  2. Bike Type Distribution:

    • Plot 3:

      • For Casual Riders:

        • Classic Bikes: 17.68%

        • Docked Bikes: 1.29%

        • Electric Bikes: 19.82%

      • For Members:

        • Classic Bikes: 31.60%

        • Electric Bikes: 29.61%

    • Electric bikes are popular among both casual and member riders.

  3. Ride Duration Analysis:

    • Plot 4: Casual riders have an average ride time of 21.91 minutes, which is approximately 8 minutes more than the average ride time for members (13.05 minutes). This suggests an opportunity to offer tailored services for casual riders who prefer longer rides.
  4. Time-Based Analysis:

    • Plot 5: Members use bikes more on weekdays, likely for commuting, while casual riders prefer weekends for leisure activities. Consider promotions or events on weekends to attract casual riders.

    • Plot 6:

      • Members peak during morning and evening hours, aligning with commuting times.

      • Casual riders show increased usage in the afternoon, indicating potential interest in leisure rides.

  5. Geographic Analysis:

    • Plot 7: Identifying top pickup and drop-off locations on the map can inform targeted marketing efforts and infrastructure improvements.

    • Plot 8: Focusing on the top 15 pickup and drop-off locations for casual riders can help in tailoring promotions and services for this specific group.

  6. Weekly Trend Analysis:

    • Plots 9 & 10: Observing a decrease in overall rides on a weekly basis, potentially due to colder months, indicates a need for seasonal promotions or incentives to maintain user engagement.

    Membership Conversion Strategies:

    • Monthly/Quarterly Events:

      • Strategy: Engaging bike events on a regular basis, offering discounted rates or free access exclusively for members.

      • Rationale: Providing members with unique and enjoyable experiences encourages them to take advantage of their membership, making it a valuable investment.

    • Location-Based Plans:

      • Strategy: Introduce targeted discounted membership plans specifically designed for the most frequented locations by riders.

      • Rationale: By aligning membership plans with riders’ preferred locations, the service becomes more personalized, increasing the likelihood of conversion.

    • Shorter Duration Plans:

      • Strategy: Create membership plans with shorter durations, such as monthly or quarterly options, to accommodate users seeking flexibility.

      • Rationale: Offering shorter-term plans caters to riders who may not commit to an annual membership, making it more accessible and appealing.

    • Weekend Annual Travel Plan:

      • Strategy: Launching a specialized annual membership plan catering to weekend riders, providing cost-effective options for those who predominantly use bikes during weekends.

      • Rationale: Recognizing and accommodating the weekend riding habits of users can attract casual riders seeking a cost-efficient plan for recreational purposes.

    • Evening Annual Travel Plan:

      • Strategy: Introducing an annual membership plan tailored for riders who use bikes primarily in the evenings, offering targeted benefits and pricing.

      • Rationale: By acknowledging and addressing the specific needs of riders who prefer evening rides, the membership becomes more attractive and aligned with their usage patterns.

In conclusion, understanding rider preferences, tailoring promotions, and strategically offering membership plans can significantly contribute to converting casual riders into long-term members. Targeted marketing efforts, coupled with a focus on user experience and convenience, can enhance the overall success of the bike-sharing program.