# Instalar paquetes necesarios
# tidyverse para importar y manipular datos
# lubridate para funciones de fecha
# ggplot para visualización
library(tidyverse)  # ayuda con la manipulación de datos
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ 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)  # ayuda con atributos de fecha
library(ggplot2)  # ayuda con la visualización de datos
library(dplyr)
# Establecer directorio de trabajo
getwd()  # muestra el directorio de trabajo actual
## [1] "C:/Cyclistic"
setwd("C:/Cyclistic")  # establece el directorio de trabajo para simplificar llamadas a datos ... asegúrate de usar tu PROPIO nombre de usuario en lugar del mío ;)

#===================== # PASO 1: RECOLECTAR DATOS #=====================

# Cargar conjuntos de datos de Divvy (archivos csv) aquí
q4_2020 <- read_csv("Divvy_Trips_2020_Q4.csv")
## Rows: 84776 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q5_2020 <- read_csv("Divvy_Trips_2020_Q5.csv")
## Rows: 200274 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q6_2020 <- read_csv("Divvy_Trips_2020_Q6.csv")
## Rows: 343005 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q7_2020 <- read_csv("Divvy_Trips_2020_Q7.csv")
## Rows: 551480 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q8_2020 <- read_csv("Divvy_Trips_2020_Q8.csv")
## Rows: 622361 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q9_2020 <- read_csv("Divvy_Trips_2020_Q9.csv")
## Rows: 532958 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q10_2020 <- read_csv("Divvy_Trips_2020_Q10.csv")
## Rows: 388653 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q11_2020 <- read_csv("Divvy_Trips_2020_Q11.csv")
## Rows: 259716 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): ride_id, rideable_type, start_station_name, end_station_name, memb...
## dbl  (6): start_station_id, end_station_id, start_lat, start_lng, end_lat, e...
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q12_2020 <- read_csv("Divvy_Trips_2020_Q12.csv")
## Rows: 131573 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (7): ride_id, rideable_type, start_station_name, start_station_id, end_...
## dbl  (4): start_lat, start_lng, end_lat, end_lng
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q1_2021 <- read_csv("Divvy_Trips_2021_Q1.csv")
## Rows: 96834 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (7): ride_id, rideable_type, start_station_name, start_station_id, end_...
## dbl  (4): start_lat, start_lng, end_lat, end_lng
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q2_2021<- read_csv("Divvy_Trips_2021_Q2.csv")
## Rows: 49622 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (7): ride_id, rideable_type, start_station_name, start_station_id, end_...
## dbl  (4): start_lat, start_lng, end_lat, end_lng
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
q3_2021<- read_csv("Divvy_Trips_2021_Q3.csv")
## Rows: 228496 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (7): ride_id, rideable_type, start_station_name, start_station_id, end_...
## dbl  (4): start_lat, start_lng, end_lat, end_lng
## dttm (2): started_at, ended_at
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

#==================================================== # PASO 2: MANIPULAR DATOS Y COMBINAR EN UN SOLO ARCHIVO #====================================================

# Comparar nombres de columnas en cada uno de los archivos
# Aunque los nombres no tienen que estar en el mismo orden, DEBEN coincidir perfectamente antes de que podamos unirlos en un solo archivo
colnames(q4_2020)
##  [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(q5_2020)
##  [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(q6_2020)
##  [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(q7_2020)
##  [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(q8_2020)
##  [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(q9_2020)
##  [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(q10_2020)
##  [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(q11_2020)
##  [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(q12_2020)
##  [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(q1_2021)
##  [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(q2_2021)
##  [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(q3_2021)
##  [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"
q4_2020 <- rename(q4_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q5_2020 <- rename(q5_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q6_2020 <- rename(q6_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q7_2020 <- rename(q7_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q8_2020 <- rename(q8_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q9_2020 <- rename(q9_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q10_2020 <- rename(q10_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)


q11_2020 <- rename(q11_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q12_2020 <- rename(q12_2020
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q1_2021 <- rename(q1_2021
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q2_2021 <- rename(q2_2021
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)

q3_2021 <- rename(q3_2021
                   ,trip_id = ride_id
                   ,bikeid = rideable_type
                   ,start_time  = started_at
                   ,end_time  = ended_at
                   ,from_station_name = start_station_name
                   ,from_station_id = start_station_id
                   ,to_station_name = end_station_name
                   ,to_station_id = end_station_id
                   ,usertype = member_casual)
# Inspeccionar los marcos de datos y buscar incongruencias
str(q4_2020)
## spc_tbl_ [84,776 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:84776] "A847FADBBC638E45" "5405B80E996FF60D" "5DD24A79A4E006F4" "2A59BBDF5CDBA725" ...
##  $ bikeid           : chr [1:84776] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:84776], format: "2020-04-26 17:45:14" "2020-04-17 17:08:54" ...
##  $ end_time         : POSIXct[1:84776], format: "2020-04-26 18:12:03" "2020-04-17 17:17:03" ...
##  $ from_station_name: chr [1:84776] "Eckhart Park" "Drake Ave & Fullerton Ave" "McClurg Ct & Erie St" "California Ave & Division St" ...
##  $ from_station_id  : num [1:84776] 86 503 142 216 125 173 35 434 627 377 ...
##  $ to_station_name  : chr [1:84776] "Lincoln Ave & Diversey Pkwy" "Kosciuszko Park" "Indiana Ave & Roosevelt Rd" "Wood St & Augusta Blvd" ...
##  $ to_station_id    : num [1:84776] 152 499 255 657 323 35 635 382 359 508 ...
##  $ start_lat        : num [1:84776] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:84776] -87.7 -87.7 -87.6 -87.7 -87.6 ...
##  $ end_lat          : num [1:84776] 41.9 41.9 41.9 41.9 42 ...
##  $ end_lng          : num [1:84776] -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ usertype         : chr [1:84776] "member" "member" "member" "member" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q5_2020)
## spc_tbl_ [200,274 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:200274] "02668AD35674B983" "7A50CCAF1EDDB28F" "2FFCDFDB91FE9A52" "58991CF1DB75BA84" ...
##  $ bikeid           : chr [1:200274] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:200274], format: "2020-05-27 10:03:52" "2020-05-25 10:47:11" ...
##  $ end_time         : POSIXct[1:200274], format: "2020-05-27 10:16:49" "2020-05-25 11:05:40" ...
##  $ from_station_name: chr [1:200274] "Franklin St & Jackson Blvd" "Clark St & Wrightwood Ave" "Kedzie Ave & Milwaukee Ave" "Clarendon Ave & Leland Ave" ...
##  $ from_station_id  : num [1:200274] 36 340 260 251 261 206 261 180 331 219 ...
##  $ to_station_name  : chr [1:200274] "Wabash Ave & Grand Ave" "Clark St & Leland Ave" "Kedzie Ave & Milwaukee Ave" "Lake Shore Dr & Wellington Ave" ...
##  $ to_station_id    : num [1:200274] 199 326 260 157 206 22 261 180 300 305 ...
##  $ start_lat        : num [1:200274] 41.9 41.9 41.9 42 41.9 ...
##  $ start_lng        : num [1:200274] -87.6 -87.6 -87.7 -87.7 -87.7 ...
##  $ end_lat          : num [1:200274] 41.9 42 41.9 41.9 41.8 ...
##  $ end_lng          : num [1:200274] -87.6 -87.7 -87.7 -87.6 -87.6 ...
##  $ usertype         : chr [1:200274] "member" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q6_2020)
## spc_tbl_ [343,005 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:343005] "8CD5DE2C2B6C4CFC" "9A191EB2C751D85D" "F37D14B0B5659BCF" "C41237B506E85FA1" ...
##  $ bikeid           : chr [1:343005] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:343005], format: "2020-06-13 23:24:48" "2020-06-26 07:26:10" ...
##  $ end_time         : POSIXct[1:343005], format: "2020-06-13 23:36:55" "2020-06-26 07:31:58" ...
##  $ from_station_name: chr [1:343005] "Wilton Ave & Belmont Ave" "Federal St & Polk St" "Daley Center Plaza" "Broadway & Cornelia Ave" ...
##  $ from_station_id  : num [1:343005] 117 41 81 303 327 327 41 115 338 84 ...
##  $ to_station_name  : chr [1:343005] "Damen Ave & Clybourn Ave" "Daley Center Plaza" "State St & Harrison St" "Broadway & Berwyn Ave" ...
##  $ to_station_id    : num [1:343005] 163 81 5 294 117 117 81 303 164 53 ...
##  $ start_lat        : num [1:343005] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:343005] -87.7 -87.6 -87.6 -87.6 -87.7 ...
##  $ end_lat          : num [1:343005] 41.9 41.9 41.9 42 41.9 ...
##  $ end_lng          : num [1:343005] -87.7 -87.6 -87.6 -87.7 -87.7 ...
##  $ usertype         : chr [1:343005] "casual" "member" "member" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q7_2020)
## spc_tbl_ [551,480 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:551480] "762198876D69004D" "BEC9C9FBA0D4CF1B" "D2FD8EA432C77EC1" "54AE594E20B35881" ...
##  $ bikeid           : chr [1:551480] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:551480], format: "2020-07-09 15:22:02" "2020-07-24 23:56:30" ...
##  $ end_time         : POSIXct[1:551480], format: "2020-07-09 15:25:52" "2020-07-25 00:20:17" ...
##  $ from_station_name: chr [1:551480] "Ritchie Ct & Banks St" "Halsted St & Roscoe St" "Lake Shore Dr & Diversey Pkwy" "LaSalle St & Illinois St" ...
##  $ from_station_id  : num [1:551480] 180 299 329 181 268 635 113 211 176 31 ...
##  $ to_station_name  : chr [1:551480] "Wells St & Evergreen Ave" "Broadway & Ridge Ave" "Clark St & Wellington Ave" "Clark St & Armitage Ave" ...
##  $ to_station_id    : num [1:551480] 291 461 156 94 301 289 140 31 191 142 ...
##  $ start_lat        : num [1:551480] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:551480] -87.6 -87.6 -87.6 -87.6 -87.6 ...
##  $ end_lat          : num [1:551480] 41.9 42 41.9 41.9 41.9 ...
##  $ end_lng          : num [1:551480] -87.6 -87.7 -87.6 -87.6 -87.6 ...
##  $ usertype         : chr [1:551480] "member" "member" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q8_2020)
## spc_tbl_ [622,361 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:622361] "322BD23D287743ED" "2A3AEF1AB9054D8B" "67DC1D133E8B5816" "C79FBBD412E578A7" ...
##  $ bikeid           : chr [1:622361] "docked_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:622361], format: "2020-08-20 18:08:14" "2020-08-27 18:46:04" ...
##  $ end_time         : POSIXct[1:622361], format: "2020-08-20 18:17:51" "2020-08-27 19:54:51" ...
##  $ from_station_name: chr [1:622361] "Lake Shore Dr & Diversey Pkwy" "Michigan Ave & 14th St" "Columbus Dr & Randolph St" "Daley Center Plaza" ...
##  $ from_station_id  : num [1:622361] 329 168 195 81 658 658 196 67 153 177 ...
##  $ to_station_name  : chr [1:622361] "Clark St & Lincoln Ave" "Michigan Ave & 14th St" "State St & Randolph St" "State St & Kinzie St" ...
##  $ to_station_id    : num [1:622361] 141 168 44 47 658 658 49 229 225 305 ...
##  $ start_lat        : num [1:622361] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:622361] -87.6 -87.6 -87.6 -87.6 -87.7 ...
##  $ end_lat          : num [1:622361] 41.9 41.9 41.9 41.9 41.9 ...
##  $ end_lng          : num [1:622361] -87.6 -87.6 -87.6 -87.6 -87.7 ...
##  $ usertype         : chr [1:622361] "member" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q9_2020)
## spc_tbl_ [532,958 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:532958] "2B22BD5F95FB2629" "A7FB70B4AFC6CAF2" "86057FA01BAC778E" "57F6DC9A153DB98C" ...
##  $ bikeid           : chr [1:532958] "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:532958], format: "2020-09-17 14:27:11" "2020-09-17 15:07:31" ...
##  $ end_time         : POSIXct[1:532958], format: "2020-09-17 14:44:24" "2020-09-17 15:07:45" ...
##  $ from_station_name: chr [1:532958] "Michigan Ave & Lake St" "W Oakdale Ave & N Broadway" "W Oakdale Ave & N Broadway" "Ashland Ave & Belle Plaine Ave" ...
##  $ from_station_id  : num [1:532958] 52 NA NA 246 24 94 291 NA NA NA ...
##  $ to_station_name  : chr [1:532958] "Green St & Randolph St" "W Oakdale Ave & N Broadway" "W Oakdale Ave & N Broadway" "Montrose Harbor" ...
##  $ to_station_id    : num [1:532958] 112 NA NA 249 24 NA 256 NA NA NA ...
##  $ start_lat        : num [1:532958] 41.9 41.9 41.9 42 41.9 ...
##  $ start_lng        : num [1:532958] -87.6 -87.6 -87.6 -87.7 -87.6 ...
##  $ end_lat          : num [1:532958] 41.9 41.9 41.9 42 41.9 ...
##  $ end_lng          : num [1:532958] -87.6 -87.6 -87.6 -87.6 -87.6 ...
##  $ usertype         : chr [1:532958] "casual" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q10_2020)
## spc_tbl_ [388,653 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:388653] "ACB6B40CF5B9044C" "DF450C72FD109C01" "B6396B54A15AC0DF" "44A4AEE261B9E854" ...
##  $ bikeid           : chr [1:388653] "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:388653], format: "2020-10-31 19:39:43" "2020-10-31 23:50:08" ...
##  $ end_time         : POSIXct[1:388653], format: "2020-10-31 19:57:12" "2020-11-01 00:04:16" ...
##  $ from_station_name: chr [1:388653] "Lakeview Ave & Fullerton Pkwy" "Southport Ave & Waveland Ave" "Stony Island Ave & 67th St" "Clark St & Grace St" ...
##  $ from_station_id  : num [1:388653] 313 227 102 165 190 359 313 125 NA 174 ...
##  $ to_station_name  : chr [1:388653] "Rush St & Hubbard St" "Kedzie Ave & Milwaukee Ave" "University Ave & 57th St" "Broadway & Sheridan Rd" ...
##  $ to_station_id    : num [1:388653] 125 260 423 256 185 53 125 313 199 635 ...
##  $ start_lat        : num [1:388653] 41.9 41.9 41.8 42 41.9 ...
##  $ start_lng        : num [1:388653] -87.6 -87.7 -87.6 -87.7 -87.7 ...
##  $ end_lat          : num [1:388653] 41.9 41.9 41.8 42 41.9 ...
##  $ end_lng          : num [1:388653] -87.6 -87.7 -87.6 -87.7 -87.7 ...
##  $ usertype         : chr [1:388653] "casual" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q11_2020)
## spc_tbl_ [259,716 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:259716] "BD0A6FF6FFF9B921" "96A7A7A4BDE4F82D" "C61526D06582BDC5" "E533E89C32080B9E" ...
##  $ bikeid           : chr [1:259716] "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:259716], format: "2020-11-01 13:36:00" "2020-11-01 10:03:26" ...
##  $ end_time         : POSIXct[1:259716], format: "2020-11-01 13:45:40" "2020-11-01 10:14:45" ...
##  $ from_station_name: chr [1:259716] "Dearborn St & Erie St" "Franklin St & Illinois St" "Lake Shore Dr & Monroe St" "Leavitt St & Chicago Ave" ...
##  $ from_station_id  : num [1:259716] 110 672 76 659 2 72 76 NA 58 394 ...
##  $ to_station_name  : chr [1:259716] "St. Clair St & Erie St" "Noble St & Milwaukee Ave" "Federal St & Polk St" "Stave St & Armitage Ave" ...
##  $ to_station_id    : num [1:259716] 211 29 41 185 2 76 72 NA 288 273 ...
##  $ start_lat        : num [1:259716] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:259716] -87.6 -87.6 -87.6 -87.7 -87.6 ...
##  $ end_lat          : num [1:259716] 41.9 41.9 41.9 41.9 41.9 ...
##  $ end_lng          : num [1:259716] -87.6 -87.7 -87.6 -87.7 -87.6 ...
##  $ usertype         : chr [1:259716] "casual" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_double(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_double(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q12_2020)
## spc_tbl_ [131,573 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:131573] "70B6A9A437D4C30D" "158A465D4E74C54A" "5262016E0F1F2F9A" "BE119628E44F871E" ...
##  $ bikeid           : chr [1:131573] "classic_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:131573], format: "2020-12-27 12:44:29" "2020-12-18 17:37:15" ...
##  $ end_time         : POSIXct[1:131573], format: "2020-12-27 12:55:06" "2020-12-18 17:44:19" ...
##  $ from_station_name: chr [1:131573] "Aberdeen St & Jackson Blvd" NA NA NA ...
##  $ from_station_id  : chr [1:131573] "13157" NA NA NA ...
##  $ to_station_name  : chr [1:131573] "Desplaines St & Kinzie St" NA NA NA ...
##  $ to_station_id    : chr [1:131573] "TA1306000003" NA NA NA ...
##  $ start_lat        : num [1:131573] 41.9 41.9 41.9 41.9 41.8 ...
##  $ start_lng        : num [1:131573] -87.7 -87.7 -87.7 -87.7 -87.6 ...
##  $ end_lat          : num [1:131573] 41.9 41.9 41.9 41.9 41.8 ...
##  $ end_lng          : num [1:131573] -87.6 -87.7 -87.7 -87.7 -87.6 ...
##  $ usertype         : chr [1:131573] "member" "member" "member" "member" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_character(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_character(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q1_2021)
## spc_tbl_ [96,834 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:96834] "E19E6F1B8D4C42ED" "DC88F20C2C55F27F" "EC45C94683FE3F27" "4FA453A75AE377DB" ...
##  $ bikeid           : chr [1:96834] "electric_bike" "electric_bike" "electric_bike" "electric_bike" ...
##  $ start_time       : POSIXct[1:96834], format: "2021-01-23 16:14:19" "2021-01-27 18:43:08" ...
##  $ end_time         : POSIXct[1:96834], format: "2021-01-23 16:24:44" "2021-01-27 18:47:12" ...
##  $ from_station_name: chr [1:96834] "California Ave & Cortez St" "California Ave & Cortez St" "California Ave & Cortez St" "California Ave & Cortez St" ...
##  $ from_station_id  : chr [1:96834] "17660" "17660" "17660" "17660" ...
##  $ to_station_name  : chr [1:96834] NA NA NA NA ...
##  $ to_station_id    : chr [1:96834] NA NA NA NA ...
##  $ start_lat        : num [1:96834] 41.9 41.9 41.9 41.9 41.9 ...
##  $ start_lng        : num [1:96834] -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ end_lat          : num [1:96834] 41.9 41.9 41.9 41.9 41.9 ...
##  $ end_lng          : num [1:96834] -87.7 -87.7 -87.7 -87.7 -87.7 ...
##  $ usertype         : chr [1:96834] "member" "member" "member" "member" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_character(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_character(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q2_2021)
## spc_tbl_ [49,622 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:49622] "89E7AA6C29227EFF" "0FEFDE2603568365" "E6159D746B2DBB91" "B32D3199F1C2E75B" ...
##  $ bikeid           : chr [1:49622] "classic_bike" "classic_bike" "electric_bike" "classic_bike" ...
##  $ start_time       : POSIXct[1:49622], format: "2021-02-12 16:14:56" "2021-02-14 17:52:38" ...
##  $ end_time         : POSIXct[1:49622], format: "2021-02-12 16:21:43" "2021-02-14 18:12:09" ...
##  $ from_station_name: chr [1:49622] "Glenwood Ave & Touhy Ave" "Glenwood Ave & Touhy Ave" "Clark St & Lake St" "Wood St & Chicago Ave" ...
##  $ from_station_id  : chr [1:49622] "525" "525" "KA1503000012" "637" ...
##  $ to_station_name  : chr [1:49622] "Sheridan Rd & Columbia Ave" "Bosworth Ave & Howard St" "State St & Randolph St" "Honore St & Division St" ...
##  $ to_station_id    : chr [1:49622] "660" "16806" "TA1305000029" "TA1305000034" ...
##  $ start_lat        : num [1:49622] 42 42 41.9 41.9 41.8 ...
##  $ start_lng        : num [1:49622] -87.7 -87.7 -87.6 -87.7 -87.6 ...
##  $ end_lat          : num [1:49622] 42 42 41.9 41.9 41.8 ...
##  $ end_lng          : num [1:49622] -87.7 -87.7 -87.6 -87.7 -87.6 ...
##  $ usertype         : chr [1:49622] "member" "casual" "member" "member" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_character(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_character(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
str(q3_2021)
## spc_tbl_ [228,496 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:228496] "CFA86D4455AA1030" "30D9DC61227D1AF3" "846D87A15682A284" "994D05AA75A168F2" ...
##  $ bikeid           : chr [1:228496] "classic_bike" "classic_bike" "classic_bike" "classic_bike" ...
##  $ start_time       : POSIXct[1:228496], format: "2021-03-16 08:32:30" "2021-03-28 01:26:28" ...
##  $ end_time         : POSIXct[1:228496], format: "2021-03-16 08:36:34" "2021-03-28 01:36:55" ...
##  $ from_station_name: chr [1:228496] "Humboldt Blvd & Armitage Ave" "Humboldt Blvd & Armitage Ave" "Shields Ave & 28th Pl" "Winthrop Ave & Lawrence Ave" ...
##  $ from_station_id  : chr [1:228496] "15651" "15651" "15443" "TA1308000021" ...
##  $ to_station_name  : chr [1:228496] "Stave St & Armitage Ave" "Central Park Ave & Bloomingdale Ave" "Halsted St & 35th St" "Broadway & Sheridan Rd" ...
##  $ to_station_id    : chr [1:228496] "13266" "18017" "TA1308000043" "13323" ...
##  $ start_lat        : num [1:228496] 41.9 41.9 41.8 42 42 ...
##  $ start_lng        : num [1:228496] -87.7 -87.7 -87.6 -87.7 -87.7 ...
##  $ end_lat          : num [1:228496] 41.9 41.9 41.8 42 42.1 ...
##  $ end_lng          : num [1:228496] -87.7 -87.7 -87.6 -87.6 -87.7 ...
##  $ usertype         : chr [1:228496] "casual" "casual" "casual" "casual" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ride_id = col_character(),
##   ..   rideable_type = col_character(),
##   ..   started_at = col_datetime(format = ""),
##   ..   ended_at = col_datetime(format = ""),
##   ..   start_station_name = col_character(),
##   ..   start_station_id = col_character(),
##   ..   end_station_name = col_character(),
##   ..   end_station_id = col_character(),
##   ..   start_lat = col_double(),
##   ..   start_lng = col_double(),
##   ..   end_lat = col_double(),
##   ..   end_lng = col_double(),
##   ..   member_casual = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
# Convertir ride_id y rideable_type a caracteres para que puedan apilarse correctamente
q4_2020 <-  mutate(q4_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid)) 
q5_2020 <-  mutate(q5_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q6_2020 <-  mutate(q6_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q7_2020 <-  mutate(q7_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q8_2020 <-  mutate(q8_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q9_2020 <-  mutate(q9_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q10_2020 <-  mutate(q10_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q11_2020 <-  mutate(q11_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q12_2020 <-  mutate(q12_2020, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q1_2021 <-  mutate(q1_2021, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q2_2021 <-  mutate(q2_2021, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
q3_2021 <-  mutate(q3_2021, trip_id = as.character(trip_id)
                   ,bikeid = as.character(bikeid))
# Convertir la columna from_station_id a tipo character en todos los conjuntos de datos
q4_2020$from_station_id <- as.character(q4_2020$from_station_id)
q5_2020$from_station_id <- as.character(q5_2020$from_station_id)
q6_2020$from_station_id <- as.character(q6_2020$from_station_id)
q7_2020$from_station_id <- as.character(q7_2020$from_station_id)
q8_2020$from_station_id <- as.character(q8_2020$from_station_id)
q9_2020$from_station_id <- as.character(q9_2020$from_station_id)
q10_2020$from_station_id <- as.character(q10_2020$from_station_id)
q11_2020$from_station_id <- as.character(q11_2020$from_station_id)
q12_2020$from_station_id <- as.character(q12_2020$from_station_id)
q1_2021$from_station_id <- as.character(q1_2021$from_station_id)
q2_2021$from_station_id <- as.character(q2_2021$from_station_id)
q3_2021$from_station_id <- as.character(q3_2021$from_station_id)
# Convertir la columna to_station_id a tipo character en todos los conjuntos de datos
q4_2020$to_station_id <- as.character(q4_2020$to_station_id)
q5_2020$to_station_id <- as.character(q5_2020$to_station_id)
q6_2020$to_station_id <- as.character(q6_2020$to_station_id)
q7_2020$to_station_id <- as.character(q7_2020$to_station_id)
q8_2020$to_station_id <- as.character(q8_2020$to_station_id)
q9_2020$to_station_id <- as.character(q9_2020$to_station_id)
q10_2020$to_station_id <- as.character(q10_2020$to_station_id)
q11_2020$to_station_id <- as.character(q11_2020$to_station_id)
q12_2020$to_station_id <- as.character(q12_2020$to_station_id)
q1_2021$to_station_id <- as.character(q1_2021$to_station_id)
q2_2021$to_station_id <- as.character(q2_2021$to_station_id)
q3_2021$to_station_id <- as.character(q3_2021$to_station_id)
# Apilar los marcos de datos individuales de cada trimestre en un gran marco de datos
all_trips <- bind_rows(q4_2020, q5_2020, q6_2020, q7_2020, q8_2020, q9_2020, q10_2020, q11_2020, q12_2020, q1_2021, q2_2021, q3_2021)
# Eliminar las columnas lat y long, ya que estos datos fueron eliminados a partir de 2020
all_trips <- all_trips %>%  
  select(-c(start_lat, start_lng, end_lat, end_lng))

#====================================================== # PASO 3: LIMPIAR Y AGREGAR DATOS PARA PREPARAR EL ANÁLISIS #======================================================

# Inspeccionar la nueva tabla que se ha creado
colnames(all_trips)  # Lista de nombres de columnas
## [1] "trip_id"           "bikeid"            "start_time"       
## [4] "end_time"          "from_station_name" "from_station_id"  
## [7] "to_station_name"   "to_station_id"     "usertype"
nrow(all_trips)  # ¿Cuántas filas hay en el marco de datos?
## [1] 3489748
dim(all_trips)  # Dimensiones del marco de datos
## [1] 3489748       9
head(all_trips)  # Ver las primeras 6 filas del marco de datos. También se puede usar tail(all_trips)
## # A tibble: 6 × 9
##   trip_id       bikeid start_time          end_time            from_station_name
##   <chr>         <chr>  <dttm>              <dttm>              <chr>            
## 1 A847FADBBC63… docke… 2020-04-26 17:45:14 2020-04-26 18:12:03 Eckhart Park     
## 2 5405B80E996F… docke… 2020-04-17 17:08:54 2020-04-17 17:17:03 Drake Ave & Full…
## 3 5DD24A79A4E0… docke… 2020-04-01 17:54:13 2020-04-01 18:08:36 McClurg Ct & Eri…
## 4 2A59BBDF5CDB… docke… 2020-04-07 12:50:19 2020-04-07 13:02:31 California Ave &…
## 5 27AD306C119C… docke… 2020-04-18 10:22:59 2020-04-18 11:15:54 Rush St & Hubbar…
## 6 356216E87513… docke… 2020-04-30 17:55:47 2020-04-30 18:01:11 Mies van der Roh…
## # ℹ 4 more variables: from_station_id <chr>, to_station_name <chr>,
## #   to_station_id <chr>, usertype <chr>
str(all_trips)  # Ver lista de columnas y tipos de datos (numérico, caracter, etc.)
## tibble [3,489,748 × 9] (S3: tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:3489748] "A847FADBBC638E45" "5405B80E996FF60D" "5DD24A79A4E006F4" "2A59BBDF5CDBA725" ...
##  $ bikeid           : chr [1:3489748] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:3489748], format: "2020-04-26 17:45:14" "2020-04-17 17:08:54" ...
##  $ end_time         : POSIXct[1:3489748], format: "2020-04-26 18:12:03" "2020-04-17 17:17:03" ...
##  $ from_station_name: chr [1:3489748] "Eckhart Park" "Drake Ave & Fullerton Ave" "McClurg Ct & Erie St" "California Ave & Division St" ...
##  $ from_station_id  : chr [1:3489748] "86" "503" "142" "216" ...
##  $ to_station_name  : chr [1:3489748] "Lincoln Ave & Diversey Pkwy" "Kosciuszko Park" "Indiana Ave & Roosevelt Rd" "Wood St & Augusta Blvd" ...
##  $ to_station_id    : chr [1:3489748] "152" "499" "255" "657" ...
##  $ usertype         : chr [1:3489748] "member" "member" "member" "member" ...
summary(all_trips)  # Resumen estadístico de los datos. Principalmente para variables numéricas
##    trip_id             bikeid            start_time                    
##  Length:3489748     Length:3489748     Min.   :2020-04-01 00:00:30.00  
##  Class :character   Class :character   1st Qu.:2020-07-14 19:38:28.00  
##  Mode  :character   Mode  :character   Median :2020-08-29 14:50:36.50  
##                                        Mean   :2020-09-10 01:21:45.98  
##                                        3rd Qu.:2020-10-20 18:14:13.00  
##                                        Max.   :2021-03-31 23:59:08.00  
##     end_time                      from_station_name  from_station_id   
##  Min.   :2020-04-01 00:10:45.00   Length:3489748     Length:3489748    
##  1st Qu.:2020-07-14 20:13:07.75   Class :character   Class :character  
##  Median :2020-08-29 15:21:13.00   Mode  :character   Mode  :character  
##  Mean   :2020-09-10 01:46:31.98                                        
##  3rd Qu.:2020-10-20 18:28:46.25                                        
##  Max.   :2021-04-06 11:00:11.00                                        
##  to_station_name    to_station_id        usertype        
##  Length:3489748     Length:3489748     Length:3489748    
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##                                                          
##                                                          
## 
# Reasignar a los valores deseados (utilizaremos las etiquetas actuales)
all_trips <- all_trips %>% 
  mutate(usertype = recode(usertype
                           ,"member" = "Subscriber"
                           ,"casual" = "Customer"))
# Verificar para asegurarse de que se hayan reasignado el número correcto de observaciones
table(all_trips$usertype)
## 
##   Customer Subscriber 
##    1430376    2059372
# Agregar columnas que indiquen la fecha, mes, día y año de cada viaje
# Esto nos permitirá agregar datos de viaje para cada mes, día o año ... antes de completar estas operaciones, solo podíamos agregar a nivel de viaje
all_trips$date <- as.Date(all_trips$start_time) # El formato predeterminado es yyyy-mm-dd
all_trips$month <- format(as.Date(all_trips$date), "%m")
all_trips$day <- format(as.Date(all_trips$date), "%d")
all_trips$year <- format(as.Date(all_trips$date), "%Y")
all_trips$day_of_week <- format(as.Date(all_trips$date), "%A")
# Agregar un cálculo de "ride_length" a all_trips (en segundos)
all_trips$ride_length <- difftime(all_trips$end_time, all_trips$start_time)
# Inspeccionar la estructura de las columnas
str(all_trips)
## tibble [3,489,748 × 15] (S3: tbl_df/tbl/data.frame)
##  $ trip_id          : chr [1:3489748] "A847FADBBC638E45" "5405B80E996FF60D" "5DD24A79A4E006F4" "2A59BBDF5CDBA725" ...
##  $ bikeid           : chr [1:3489748] "docked_bike" "docked_bike" "docked_bike" "docked_bike" ...
##  $ start_time       : POSIXct[1:3489748], format: "2020-04-26 17:45:14" "2020-04-17 17:08:54" ...
##  $ end_time         : POSIXct[1:3489748], format: "2020-04-26 18:12:03" "2020-04-17 17:17:03" ...
##  $ from_station_name: chr [1:3489748] "Eckhart Park" "Drake Ave & Fullerton Ave" "McClurg Ct & Erie St" "California Ave & Division St" ...
##  $ from_station_id  : chr [1:3489748] "86" "503" "142" "216" ...
##  $ to_station_name  : chr [1:3489748] "Lincoln Ave & Diversey Pkwy" "Kosciuszko Park" "Indiana Ave & Roosevelt Rd" "Wood St & Augusta Blvd" ...
##  $ to_station_id    : chr [1:3489748] "152" "499" "255" "657" ...
##  $ usertype         : chr [1:3489748] "Subscriber" "Subscriber" "Subscriber" "Subscriber" ...
##  $ date             : Date[1:3489748], format: "2020-04-26" "2020-04-17" ...
##  $ month            : chr [1:3489748] "04" "04" "04" "04" ...
##  $ day              : chr [1:3489748] "26" "17" "01" "07" ...
##  $ year             : chr [1:3489748] "2020" "2020" "2020" "2020" ...
##  $ day_of_week      : chr [1:3489748] "domingo" "viernes" "miércoles" "martes" ...
##  $ ride_length      : 'difftime' num [1:3489748] 1609 489 863 732 ...
##   ..- attr(*, "units")= chr "secs"
# Convertir "ride_length" de Factor a numérico para poder realizar cálculos en los datos
is.factor(all_trips$ride_length)
## [1] FALSE
all_trips$ride_length <- as.numeric(as.character(all_trips$ride_length))
is.numeric(all_trips$ride_length)
## [1] TRUE
# Establecer opciones para imprimir números sin notación científica
options(scipen = 999)
# Ahora, cuando imprimas números, no se mostrarán en notación científica
# Eliminar datos "malos"
# El marco de datos incluye algunas entradas cuando las bicicletas fueron retiradas de los muelles y revisadas por calidad por Divvy o cuando ride_length fue negativo
# Crearemos una nueva versión del marco de datos (v2) ya que se están eliminando datos
all_trips_v2 <- all_trips[!(all_trips$from_station_name == "HQ QR" | all_trips$ride_length < 0), ]
# Sumar valores nulos en todo el marco de datos
total_nulos <- sum(is.na(all_trips_v2))
# Eliminar filas con valores nulos en cualquier columna
all_trips_v2 <- na.omit(all_trips_v2)

#===================================== # PASO 4: CONDUCIR ANÁLISIS DESCRIPTIVO #=====================================

# Análisis descriptivo de ride_length (todas las cifras en segundos)
summary(all_trips_v2$ride_length)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       0     485     885    1683    1615 3523202
# Comparar usuarios regulares y usuarios ocasionales
aggregate(ride_length ~ usertype, data = all_trips_v2, FUN = mean)
##     usertype ride_length
## 1   Customer    2727.148
## 2 Subscriber     955.989
aggregate(ride_length ~ usertype, data = all_trips_v2, FUN = median)
##     usertype ride_length
## 1   Customer        1298
## 2 Subscriber         696
aggregate(ride_length ~ usertype, data = all_trips_v2, FUN = max)
##     usertype ride_length
## 1   Customer     3341033
## 2 Subscriber     3523202
aggregate(ride_length ~ usertype, data = all_trips_v2, FUN = min)
##     usertype ride_length
## 1   Customer           0
## 2 Subscriber           0
# Asegúrate de que los días de la semana estén ordenados correctamente
all_trips_v2$day_of_week <- ordered(all_trips_v2$day_of_week,
                                    levels = c("domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"))
# Ahora, ejecutemos el tiempo promedio de viaje por cada día para miembros vs usuarios ocasionales
aggregate(ride_length ~ usertype + day_of_week, data = all_trips_v2, FUN = mean)
##      usertype day_of_week ride_length
## 1    Customer     domingo   3068.1051
## 2  Subscriber     domingo   1088.6371
## 3    Customer       lunes   2729.2281
## 4  Subscriber       lunes    905.6358
## 5    Customer      martes   2455.6268
## 6  Subscriber      martes    898.2676
## 7    Customer   miércoles   2452.9892
## 8  Subscriber   miércoles    902.8526
## 9    Customer      jueves   2615.7031
## 10 Subscriber      jueves    901.8053
## 11   Customer     viernes   2595.3146
## 12 Subscriber     viernes    934.0045
## 13   Customer      sábado   2838.4543
## 14 Subscriber      sábado   1061.0147
# Promedio de duración de viaje por tipo de bicicleta y usuario
# Convierte las columnas a factores
all_trips_v2$bikeid <- as.factor(all_trips_v2$bikeid)
all_trips_v2$usertype <- as.factor(all_trips_v2$usertype)

# Calcula el promedio de duración de viaje por tipo de bicicleta y usuario
promedio_duracion <- all_trips_v2 %>%
  group_by(bikeid, usertype) %>%
  summarise(average_duration = mean(ride_length), .groups = 'drop') %>%
  arrange(usertype, desc(average_duration))

# Crea un gráfico de barras para visualizar el promedio de duración por tipo de bicicleta y usuario
library(ggplot2)
ggplot(promedio_duracion, aes(x = bikeid, y = average_duration, fill = usertype)) +
  geom_bar(stat = "identity", position = "dodge", color = "white") +
  labs(title = "Promedio de Duración de Viaje por Tipo de Bicicleta y Usuario",
       x = "Tipo de Bicicleta",
       y = "Duración Promedio (segundos)",
       fill = "Tipo de Usuario") +
  theme_minimal() +
  scale_y_continuous(labels = scales::comma_format(scale = 1e+0))

# Promedio de duración de viaje por tipo de bicicleta
# Convierte 'rideable_type' a factor
all_trips_v2$bikeid <- as.factor(all_trips_v2$bikeid)

# Calcula el promedio de duración de viaje por tipo de bicicleta
promedio_duracion <- all_trips_v2 %>%
  group_by(bikeid) %>%
  summarise(average_duration = mean(ride_length), .groups = 'drop') %>%
  arrange(desc(average_duration))

# Crea un gráfico de barras para visualizar el promedio de duración por tipo de bicicleta
ggplot(promedio_duracion, aes(x = bikeid, y = average_duration, fill = bikeid)) +
  geom_bar(stat = "identity", color = "white") +
  labs(title = "Promedio de Duración de Viaje por Tipo de Bicicleta",
       x = "Tipo de Bicicleta",
       y = "Duración Promedio (segundos)",
       fill = "Tipo de Bicicleta") +
  theme_minimal() +
  scale_y_continuous(labels = scales::comma_format(scale = 1e+0))

# Creemos un gráfico para visualizar el número de viajes por tipo de usuario
all_trips_v2 %>%
  mutate(weekday = wday(start_time, label = TRUE)) %>%
  group_by(usertype, weekday) %>%
  summarise(number_of_rides = n(), .groups = 'drop') %>%
  arrange(usertype, weekday) %>%
  ggplot(aes(x = weekday, y = number_of_rides, fill = usertype)) +
  geom_col(position = "dodge") +
  labs(title = "Número de viajes por tipo de usuario y día de la semana",
       x = "Día de la semana",
       y = "Número de viajes",
       fill = "Tipo de usuario") +
  theme_minimal() +
  scale_y_continuous(labels = scales::comma_format(scale = 1e+0))

# Creemos un gráfico para visualizar la duración promedio por tipo de usuario y día de la semana
all_trips_v2 %>%
  mutate(weekday = wday(start_time, label = TRUE)) %>%
  group_by(usertype, weekday) %>%
  summarise(number_of_rides = n(),
            average_duration = mean(ride_length), .groups = 'drop') %>%
  arrange(usertype, weekday) %>%
  ggplot(aes(x = weekday, y = average_duration, fill = usertype)) +
  geom_col(position = "dodge") +
  labs(title = "Duración promedio por tipo de usuario y día de la semana",
       x = "Día de la semana",
       y = "Duración promedio (segundos)",
       fill = "Tipo de usuario") +
  theme_minimal() +
  scale_y_continuous(labels = scales::comma_format(scale = 1e+0))

#================================================= # PASO 5: EXPORTAR ARCHIVO DE RESUMEN PARA UN ANÁLISIS ADICIONAL #=================================================

# Crea un archivo CSV que visualizaremos en Excel, Tableau o mi software de presentación
counts <- aggregate(all_trips_v2$ride_length ~ all_trips_v2$usertype + all_trips_v2$day_of_week, FUN = mean)
write.csv(counts, file = 'C:/Cyclistic/counts.csv', row.names = FALSE)