---
title: "Cyclistic Bike Share Report"
author: "Omar Morales Muñoz"
date: "2024-11-21"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r load packages, message=FALSE, warning=FALSE}
library(tidyverse)
library(skimr)
library(ggplot2)
library(dplyr)
library(lubridate)
library(scales)
```


## Cyclistic case study

### Business task

Analyze bike usage of Cyclic customers to Identify differences between annual members and casual riders.

### Data sources

```{r load data}
# Data, read one 1 file at a time, if running this online in Posit load only first 
trips_2014_Q1Q2 <- read_csv("Cyclistic_Data/Divvy_Trips_2014_Q1Q2.csv")
# trips_2014_Q3_07 <- read_csv("Cyclistic_Data/Divvy_Trips_2014-Q3-07.csv")
# trips_2014_Q3_0809 <- read_csv("Cyclistic_Data/Divvy_Trips_2014-Q3-0809.csv")
# trips_2014_Q4 <- read_csv("Cyclistic_Data/Divvy_Trips_2014-Q4.csv")
```

This analysis will be performed in the information collected for the trips that took place in the first half of the year 2014. The information collected has these characteristics: 

```{r glimpse of data}
glimpse(trips_2014_Q1Q2)
```
Additional information about the data:

```{r summary of data}
summary(trips_2014_Q1Q2)
```

In order to run this analysis in Posit just the first half of the year 2014 will be included, to get the full analysis please open trip_analysis.R.

```{r message=FALSE}
allData <- trips_2014_Q1Q2
```

The data collected has two kind of user types: customer and subscribers, the data of the subscribers don't have year of birth and gender, to make sure all subscribers have all data we will use this query:

```{r check subscribers data}
allData %>%
  filter( is.na(birthyear) |  is.na(gender)) %>%
  count(usertype)
```
To avoid using incomplete data we will remove these 34 rows:

```{r removing incomplete data}
allData <- allData %>%
  filter(usertype == "Customer" | (usertype == "Subscriber" &  
                                     ! is.na(birthyear) & ! is.na(gender)))
```

Now, lets check if the trip duration calculation is correct:

```{r verifying trip duration}
allData %>%
  mutate(startime_time = mdy_hm(starttime),
         stoptime_time = mdy_hm(stoptime)) %>%
  mutate(newTripDuration = difftime(stoptime_time, startime_time, units = "secs"),
         newTripDurationNum = as.numeric(difftime(stoptime_time, startime_time, units = "secs"))) %>% 
  select(starttime, stoptime, tripduration, newTripDuration, newTripDurationNum)
```

The trip duration is not calculated in the right way, to correct this, we will add a new column with the right calculation:

```{r right trip duration calculation}
allData <- allData %>%
  mutate(startime_time = mdy_hm(starttime),
         stoptime_time = mdy_hm(stoptime)) %>%
  mutate(newTripDuration = difftime(stoptime_time, startime_time, units = "secs"),
         newTripDurationNum = as.numeric(difftime(stoptime_time, startime_time, units = "secs")))
```

Now here is more information about the data after adding the right trip duration:

```{r information about data}
skim_without_charts(allData)
```

## Information about the data

Now that the have consistent data we will get some information about it, lets show the mean and the max trip duration by user type:

```{r mean and max trip duration by user type}
allData %>% 
  group_by(usertype) %>% 
  summarise(mean_tripduration = mean(newTripDurationNum),
            max_tripduration = max(newTripDurationNum))
```
This is the the mean and the max trip duration by gender:

```{r mean and max trip duration by gender}
allData %>% 
  group_by(gender) %>% 
  summarise(mean_tripduration = mean(newTripDurationNum),
            max_tripduration = max(newTripDurationNum))
```

Here is the mean and max of the data combining user type and gender:

```{r mean and max trip duration by user type and gender}
allData %>% 
  group_by(usertype, gender) %>% 
  summarise(mean_tripduration_hrs = mean(newTripDurationNum), 
            max_tripduration_hrs = max(newTripDurationNum) ,
            .groups = 'drop')
```


## Graphical analysis of the data

This is how the data is distributed by user type:

```{r usertype pie chart}
# Dataframe for usertype pie chart
df_usertype <- allData %>%
  group_by(usertype) %>%
  count() %>%
  ungroup() %>%
  mutate(perc = `n` / sum(`n`)) %>%
  arrange(perc) %>%
  mutate(labels = scales::percent(perc))

# Pie chart for usertype
ggplot(df_usertype, aes(x = "", y = perc, fill = usertype)) +
  coord_polar(theta = "y") + 
  geom_col(color = "black") +
  geom_text(aes(label = labels),
            position = position_stack(vjust = 0.5),
            show.legend = FALSE) +
  guides(fill = guide_legend(title = "")) +
  theme_void() + 
  ggtitle("User type") + 
  theme(plot.title = element_text(hjust = 0.5))

```

Subscribers distribution by gender is this:

```{r subscribers by gender}
# Dataframe for gender in subscribers pie chart
df_subsgender <- allData %>%
  filter(usertype == "Subscriber") %>%
  group_by(gender) %>%
  count() %>%
  ungroup() %>%
  mutate(perc = `n` / sum(`n`)) %>%
  arrange(perc) %>%
  mutate(labels = scales::percent(perc))

# Pie chart for usertype
ggplot(df_subsgender, aes(x = "", y = perc, fill = gender)) +
  coord_polar(theta = "y") + 
  geom_col(color = "black") +
  geom_text(aes(label = labels),
            position = position_stack(vjust = 0.5),
            show.legend = FALSE) +
  guides(fill = guide_legend(title = "")) +
  theme_void() + 
  ggtitle("Subscribers by gender") + 
  theme(plot.title = element_text(hjust = 0.5))
```

Another important piece of information about the data is the distribution of subscribers by their year of birth:

```{r subscribers by birth of year}
# Dataframe for birthyear distribution of subscribers
options(scipen=10000)
df_subsbirthyear <- allData %>%
  filter(usertype == "Subscriber") %>%
  group_by(period_birth=cut(birthyear,
                  breaks = c(1890,1940,1960,1980,2000), 
                  labels = c("1890-1940", "1941-1960", "1961-1980", "1981-2000")))

# Graph of subscribers by birthyear
ggplot(data = df_subsbirthyear, aes (x = period_birth)) +
  geom_bar(fill="lightblue") + 
  geom_text(stat = "count",aes(label = paste0(after_stat(count)
    ," (",scales::percent(after_stat(count)/ sum(after_stat(count))),")")
    , vjust = -0.5)) +
  theme_minimal() +
  ggtitle("Subscribers by birth year") + 
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank()) +
  xlab("Birth year")
```



Finally the birth of year distribution by gender will be this:

```{r subscribers by gendeer and birth of year}
# Graph of subscribers by birthyear and gender
ggplot(data = df_subsbirthyear, aes (x = period_birth, fill = gender)) +
  geom_bar() + 
  geom_text(stat = "count",aes(label = paste0(after_stat(count)
    ," (",scales::percent(after_stat(count)/ sum(after_stat(count))),")")
    , vjust = -0.5)) +
  theme_minimal() +
  ggtitle("Subscribers by sex and birth year") + 
  guides(fill = guide_legend(title = "")) +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank()) +
  xlab("Birth year")
```


