About Data Analysis Report

This RMarkdown file contains the report of the data analysis done for the project on forecasting daily bike rental demand using time series models in R. It contains analysis such as data exploration, summary statistics and building the time series models. The final report was completed on Sat Dec 23 19:20:27 2023.

Data Description:

This dataset contains the daily count of rental bike transactions between years 2011 and 2012 in Capital bikeshare system with the corresponding weather and seasonal information.

Data Source: https://archive.ics.uci.edu/ml/datasets/bike+sharing+dataset

Relevant Paper:

Fanaee-T, Hadi, and Gama, Joao. Event labeling combining ensemble detectors and background knowledge, Progress in Artificial Intelligence (2013): pp. 1-15, Springer Berlin Heidelberg

Task One: Load and explore the data

# Install and load the readr and dplyr packages

install.packages("readr") 
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
install.packages("dplyr")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(readr) 
library(dplyr)
## 
## 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
# Specify the URL of the Bike Sharing Dataset
url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/00275/Bike-Sharing-Dataset.zip"
temp <- tempfile(fileext = ".zip")
download.file(url, temp)

# Unzip the downloaded file

unzip(temp, exdir = ".")

# List the files in the unzipped directory

files<- list.files(path = ".", pattern = "hour.csv", full.names =
TRUE)

# Load file
library(readr) 
hour <- read_csv("hour.csv") 
## Rows: 17379 Columns: 17
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl  (16): instant, season, yr, mnth, hr, holiday, weekday, workingday, weat...
## date  (1): dteday
## 
## ℹ 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.
head(hour)
## # A tibble: 6 × 17
##   instant dteday     season    yr  mnth    hr holiday weekday workingday
##     <dbl> <date>      <dbl> <dbl> <dbl> <dbl>   <dbl>   <dbl>      <dbl>
## 1       1 2011-01-01      1     0     1     0       0       6          0
## 2       2 2011-01-01      1     0     1     1       0       6          0
## 3       3 2011-01-01      1     0     1     2       0       6          0
## 4       4 2011-01-01      1     0     1     3       0       6          0
## 5       5 2011-01-01      1     0     1     4       0       6          0
## 6       6 2011-01-01      1     0     1     5       0       6          0
## # ℹ 8 more variables: weathersit <dbl>, temp <dbl>, atemp <dbl>, hum <dbl>,
## #   windspeed <dbl>, casual <dbl>, registered <dbl>, cnt <dbl>
# Load data daily

library(readr)
day<- read_csv("day.csv") 
## Rows: 731 Columns: 16
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl  (15): instant, season, yr, mnth, holiday, weekday, workingday, weathers...
## date  (1): dteday
## 
## ℹ 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.
head(day)
## # A tibble: 6 × 16
##   instant dteday     season    yr  mnth holiday weekday workingday weathersit
##     <dbl> <date>      <dbl> <dbl> <dbl>   <dbl>   <dbl>      <dbl>      <dbl>
## 1       1 2011-01-01      1     0     1       0       6          0          2
## 2       2 2011-01-02      1     0     1       0       0          0          2
## 3       3 2011-01-03      1     0     1       0       1          1          1
## 4       4 2011-01-04      1     0     1       0       2          1          1
## 5       5 2011-01-05      1     0     1       0       3          1          1
## 6       6 2011-01-06      1     0     1       0       4          1          1
## # ℹ 7 more variables: temp <dbl>, atemp <dbl>, hum <dbl>, windspeed <dbl>,
## #   casual <dbl>, registered <dbl>, cnt <dbl>
## Describe and explore the data- Daily Data

# Finding co relation between week days and actual count

colnames_day<- colnames(day)
print(colnames_day)
##  [1] "instant"    "dteday"     "season"     "yr"         "mnth"      
##  [6] "holiday"    "weekday"    "workingday" "weathersit" "temp"      
## [11] "atemp"      "hum"        "windspeed"  "casual"     "registered"
## [16] "cnt"
# Finding missing values in daily data

# Check for missing values and calculate the total for each column

missing_values_day<- colSums(is.na(day))

# Display the total missing values for each column

print(missing_values_day)
##    instant     dteday     season         yr       mnth    holiday    weekday 
##          0          0          0          0          0          0          0 
## workingday weathersit       temp      atemp        hum  windspeed     casual 
##          0          0          0          0          0          0          0 
## registered        cnt 
##          0          0
# Initialize a vector to store counts for each weekday

weekday_counts <- numeric(6)

# Set up a layout with separate panels for each weekday

par(mfrow = c(2, 4), mar = c(4, 4, 2, 1))

# Create individual plots for each weekday
for (i in 0:6) {
  hist_data <- day$registered[day$weekday == i]
  
  # Plot the histogram for the "registered" column
  hist(hist_data, 
       main = paste("Histogram for Registered (Weekday ", i, ")", sep = ""), 
       xlab = "Registered", 
       col = "skyblue", 
       border = "black", 
       xlim = c(0, max(day$registered)))
}

# Calculate standard deviation for "registered" column for each weekday

std_dev_by_weekday<- tapply(day$registered, day$weekday, sd)

# Display the results

for (i in 0:6) { cat("Standard deviation for Registered (Weekday", i,
"):", std_dev_by_weekday[i + 1], "\n") }
## Standard deviation for Registered (Weekday 0 ): 1179.713 
## Standard deviation for Registered (Weekday 1 ): 1504.216 
## Standard deviation for Registered (Weekday 2 ): 1549.462 
## Standard deviation for Registered (Weekday 3 ): 1723.71 
## Standard deviation for Registered (Weekday 4 ): 1642.753 
## Standard deviation for Registered (Weekday 5 ): 1494.999 
## Standard deviation for Registered (Weekday 6 ): 1358.069
# Create individual plots for each weekday for Actual count

for (i in 0:6) {
  hist_data <- day$registered[day$weekday == i]
  
  # Plot the histogram for the "registered" column
  hist(hist_data, 
       main = paste("Histogram for Registered (Weekday ", i, ")", sep = ""), 
       xlab = "Registered", 
       col = "skyblue", 
       border = "black", 
       xlim = c(0, max(day$registered)))
}

# Calculate standard deviation for "cnt" column for each weekday

std_dev_by_weekday <- tapply(day$cnt, day$weekday, sd)

# Display the results

for (i in 0:6) { cat("Standard deviation for Actual Count (Weekday", i,
"):", std_dev_by_weekday[i + 1], "\n") }
## Standard deviation for Actual Count (Weekday 0 ): 1872.497 
## Standard deviation for Actual Count (Weekday 1 ): 1793.074 
## Standard deviation for Actual Count (Weekday 2 ): 1826.912 
## Standard deviation for Actual Count (Weekday 3 ): 2038.096 
## Standard deviation for Actual Count (Weekday 4 ): 1939.433 
## Standard deviation for Actual Count (Weekday 5 ): 1874.625 
## Standard deviation for Actual Count (Weekday 6 ): 2196.693
# Calculate the difference between "registered" and "actual" for each weekday

difference_by_weekday <- tapply(day$cnt - day$registered, day$weekday,
sum)

# Plot: Difference between Registered and Actual by Weekday

barplot(difference_by_weekday, main = "Difference (Actual - Registered)
by Weekday", xlab = "Weekday", ylab = "Sum of Difference", col =
"skyblue", border = "black", names.arg =
levels(as.factor(day$weekday)))

# 2 : Now we see is there any correlation between other variables with the difference

# Install the corrplot package

install.packages("corrplot")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
# Load the corrplot package

library(corrplot) 
## corrplot 0.92 loaded
# Calculate the difference between "cnt" and"registered" 
difference_by_weekday <- tapply(day$cnt - day$registered,day$weekday, sum)

# Create a data frame with the variables of interest

correlation_data<- aggregate(cbind(difference_by_weekday, weathersit,
temp, hum, windspeed) ~ weekday, day, sum)
## Warning in cbind(difference_by_weekday, weathersit, temp, hum, windspeed):
## number of rows of result is not a multiple of vector length (arg 1)
# Calculate the correlation matrix

cor_matrix <- cor(correlation_data[, -1]) 

# Print the correlation matrix

print(cor_matrix)
##                       difference_by_weekday  weathersit       temp         hum
## difference_by_weekday            1.00000000 -0.08555815 -0.5528964 -0.65328945
## weathersit                      -0.08555815  1.00000000  0.5825081  0.35809662
## temp                            -0.55289639  0.58250811  1.0000000  0.15647983
## hum                             -0.65328945  0.35809662  0.1564798  1.00000000
## windspeed                        0.12343840  0.04013501 -0.4391881  0.01810159
##                         windspeed
## difference_by_weekday  0.12343840
## weathersit             0.04013501
## temp                  -0.43918807
## hum                    0.01810159
## windspeed              1.00000000
# Plot the correlation matrix

corrplot::corrplot(cor_matrix, method = "square", type = "upper", tl.cex
= 0.7)

Task Two: Create interactive time series plots

## Read about the timetk package
# ?timetk
# Load the necessary libraries
library(ggplot2)
install.packages("plotly")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(plotly)
## 
## 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
# Convert "dteday" to Date class
day$dteday <- as.Date(day$dteday)

# Create a time series plot using ggplot2
p <- ggplot(day, aes(x = dteday, y = cnt, color = as.factor(weekday))) +
  geom_line() +
  labs(title = "Interactive Time Series Plot for cnt by Weekday") +
  scale_color_manual(values = 1:7, labels = levels(as.factor(day$weekday))) +
  theme_minimal()

# Convert ggplot to plotly
p <- ggplotly(p)

# Display the interactive plot
p

Task Three: Smooth time series data

# Install and load necessary packages
install.packages(c("zoo", "TTR"))
## Installing packages into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(zoo)
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(TTR)

# Load necessary packages
library(ggplot2)

# Convert "dteday" to Date class
day$dteday <- as.Date(day$dteday)

# Create a time series object
ts_data <- zoo(day$cnt, order.by = day$dteday)

# Define the window size for the moving average
window_size <- 7  # You can adjust this value based on your preference

# Apply the simple moving average
smoothed_ts <- SMA(ts_data, n = window_size)

# Create a data frame for ggplot2
plot_data <- data.frame(
  dteday = index(ts_data),
  cnt = coredata(ts_data),
  smoothed_cnt = coredata(smoothed_ts)
)

# Plot using ggplot2
ggplot(plot_data, aes(x = dteday)) +
  geom_line(aes(y = cnt), color = "blue") +
  geom_line(aes(y = smoothed_cnt), color = "red", size = 1.5) +
  labs(title = "Original vs. Smoothed Time Series", y = "cnt") +
  theme_minimal() +
  theme(legend.position = "top") +
  scale_color_manual(values = c("Original" = "blue", "Smoothed" = "red"))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 6 rows containing missing values (`geom_line()`).

Task Four: Decompose and assess the stationarity of time series data

# Load necessary packages
library(ggplot2)
library(stats)
install.packages("tseries")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(tseries)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
# Convert "dteday" to Date class
day$dteday <- as.Date(day$dteday)

# Create a time series object
ts_data <- ts(day$cnt, start = min(day$dteday), end = max(day$dteday), frequency = 7)

# Decompose the time series
decomposition <- decompose(ts_data)

# Plot the original time series, trend, seasonality, and remainder
par(mfrow = c(4, 1))
plot(ts_data, main = "Original Time Series", col = "blue")
plot(decomposition$trend, main = "Trend Component", col = "red")
plot(decomposition$seasonal, main = "Seasonal Component", col = "green")
plot(decomposition$random, main = "Remainder (Residuals)", col = "purple")

# Check for stationarity using Augmented Dickey-Fuller test
adf_test <- adf.test(ts_data)
## Warning in adf.test(ts_data): p-value smaller than printed p-value
cat("ADF Test p-value:", adf_test$p.value, "\n")
## ADF Test p-value: 0.01
# Plot the autocorrelation function (ACF) and partial autocorrelation function (PACF)
par(mfrow = c(1, 2))
acf(ts_data, main = "ACF of Time Series", col = "blue")
pacf(ts_data, main = "PACF of Time Series", col = "red")

Task Five: Fit and forecast time series data using ARIMA models

# Load necessary packages
install.packages("forecast")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(forecast)

# Assuming ts_data is your time series object
ts_data <- ts(day$cnt, start = min(day$dteday), end = max(day$dteday), frequency = 7)

# Specify the number of observations for training
train_size <- floor(length(ts_data) * 0.8)  # 80% for training

# Create the training and testing sets using indexing
train_data <- ts_data[1:train_size]
test_data <- ts_data[(train_size + 1):length(ts_data)]


# Plot ACF
acf(ts_data, main = "Autocorrelation Function (ACF) for cnt", col = "blue")

# Plot PACF
pacf(ts_data, main = "Partial Autocorrelation Function (PACF) for cnt", col = "red")

# Perform differencing
d <- ndiffs(ts_data)

# Perform seasonal differencing (if needed)
D <- nsdiffs(ts_data)

# Plot ACF
acf(ts_data, main = "Autocorrelation Function (ACF) for cnt", col = "blue")

# Plot PACF
pacf(ts_data, main = "Partial Autocorrelation Function (PACF) for cnt", col = "red")

# Fit the ARIMA(6,0,0) model using the training set
arima_model <- arima(train_data, order = c(6, 0, 0))

# Print the summary of the ARIMA model
print(summary(arima_model))
## 
## Call:
## arima(x = train_data, order = c(6, 0, 0))
## 
## Coefficients:
##          ar1     ar2     ar3     ar4     ar5     ar6  intercept
##       0.5078  0.0739  0.0457  0.0478  0.0761  0.1980  4388.2280
## s.e.  0.0153  0.0172  0.0172  0.0172  0.0172  0.0153   278.3301
## 
## sigma^2 estimated as 835244:  log likelihood = -33672.55,  aic = 67361.11
## 
## Training set error measures:
##                    ME     RMSE     MAE       MPE     MAPE      MASE        ACF1
## Training set 1.654463 913.9167 652.268 -41.50538 54.88436 0.9062317 -0.01420623
# Forecast on the training data using the ARIMA(6,0,0) model
forecast_values_train <- forecast(arima_model, h = length(train_data))

# Evaluate accuracy
accuracy_train <- accuracy(forecast_values_train)
print(accuracy_train)
##                    ME     RMSE     MAE       MPE     MAPE      MASE        ACF1
## Training set 1.654463 913.9167 652.268 -41.50538 54.88436 0.9062317 -0.01420623
# Validating Model


# Initialize an empty vector to store forecast values
forecast_values <- numeric(0)

# Forecast one period ahead and update the model with observed values
for (i in 1:(length(ts_data) - train_size)) {
  forecast_step <- forecast(arima_model, h = 1)
  forecast_values <- c(forecast_values, forecast_step$mean)
  
  # Update the model with the observed value
  arima_model <- Arima(ts_data[1:(train_size + i + 1)], model = arima_model)
}


# Evaluate accuracy
accuracy_train <- accuracy(forecast_values_train)
print(accuracy_train)
##                    ME     RMSE     MAE       MPE     MAPE      MASE        ACF1
## Training set 1.654463 913.9167 652.268 -41.50538 54.88436 0.9062317 -0.01420623
# Now forecast_values contains the forecast for the entire test_data period
accuracy(forecast_values, test_data)
##                ME     RMSE      MAE       MPE     MAPE
## Test set 25.35871 557.6584 404.4182 -34.54629 41.92066
# Forecast the next 100 days beyond the existing data
forecast_values_future <- predict(arima_model, n.ahead  = 100)
print(forecast_values_future)
## $pred
## Time Series:
## Start = 5113 
## End = 5212 
## Frequency = 1 
##   [1] 2323.074 2127.273 2040.991 1880.228 1894.069 2103.627 2236.104 2266.472
##   [9] 2272.596 2263.247 2285.367 2349.212 2411.670 2455.144 2486.309 2511.085
##  [17] 2540.180 2577.681 2617.170 2653.485 2686.003 2715.915 2745.668 2776.639
##  [25] 2808.067 2838.768 2868.231 2896.564 2924.281 2951.786 2979.063 3005.887
##  [33] 3032.095 3057.666 3082.697 3107.298 3131.503 3155.283 3178.602 3201.450
##  [41] 3223.846 3245.822 3267.397 3288.574 3309.352 3329.732 3349.722 3369.333
##  [49] 3388.576 3407.458 3425.984 3444.160 3461.991 3479.484 3496.648 3513.488
##  [57] 3530.010 3546.220 3562.123 3577.727 3593.035 3608.054 3622.790 3637.247
##  [65] 3651.432 3665.348 3679.001 3692.397 3705.540 3718.434 3731.085 3743.497
##  [73] 3755.674 3767.622 3779.344 3790.844 3802.127 3813.197 3824.058 3834.714
##  [81] 3845.169 3855.426 3865.489 3875.362 3885.049 3894.553 3903.878 3913.026
##  [89] 3922.001 3930.807 3939.447 3947.923 3956.240 3964.399 3972.404 3980.258
##  [97] 3987.963 3995.524 4002.941 4010.218
## 
## $se
## Time Series:
## Start = 5113 
## End = 5212 
## Frequency = 1 
##   [1] 1024.989 1068.884 1093.347 1112.229 1135.004 1194.167 1241.757 1276.999
##   [9] 1304.264 1327.566 1350.584 1377.337 1403.476 1427.214 1448.452 1467.843
##  [17] 1486.294 1504.572 1522.317 1539.167 1554.998 1569.899 1584.068 1597.691
##  [25] 1610.782 1623.304 1635.236 1646.601 1657.450 1667.838 1677.793 1687.330
##  [33] 1696.456 1705.187 1713.545 1721.552 1729.227 1736.586 1743.640 1750.402
##  [41] 1756.885 1763.103 1769.068 1774.792 1780.284 1785.554 1790.613 1795.468
##  [49] 1800.130 1804.606 1808.904 1813.031 1816.995 1820.803 1824.460 1827.974
##  [57] 1831.350 1834.594 1837.711 1840.707 1843.586 1846.352 1849.012 1851.568
##  [65] 1854.025 1856.387 1858.658 1860.842 1862.941 1864.960 1866.901 1868.767
##  [73] 1870.562 1872.288 1873.948 1875.544 1877.080 1878.556 1879.977 1881.343
##  [81] 1882.657 1883.921 1885.137 1886.307 1887.432 1888.515 1889.557 1890.559
##  [89] 1891.523 1892.450 1893.342 1894.201 1895.027 1895.822 1896.587 1897.322
##  [97] 1898.030 1898.712 1899.367 1899.998

Task Six: Findings and Conclusions

#Data Exploration Findings:

#1: Exploring data, i can say data is complete, no missing values observed in entire data set(daily)
#2: If i plot actual(cnt column) vs registered data value, it seems, actual bike rides are higher        than registration made. This could be a one reason to mismatch logistic supply and may lead to       customer dissatisfaction.
#3: For each day actual bookings data distribution  are left skewed and hence it is not a normal         distribution. 
#4: Correlation plot: It is interesting to find that out of 4 other variables , humidity and             temperature are in negative association with actual bookings. In other words, when there is rise     in humidity/temperature, there might be a chance of fall in actual bookings. 

#Time Series plot Findings and ARIMA model Selection conclusion

#1: While checking ADF test , p value is <0.05 , which reinforce that null hypothesis is rejected and     hence converted time series is stationary. 
#2: ACF plot and PACF plot gives us p,d,q values and these values are as under;
    # p=6, q=0, d=0
#3: So selected arima model is ARIMA(6,0,0)
#4: To measure performance of selected ARIMA(6,0,0) model , i have devided data set into train(80%)      nd test data(20%). 
#5: Performance matrix for test data is found better than train data( MAPE_Train = 54, MAPE_Test =       37)
#6: I have predicted next 100 days bookings using ARIMA(6,0,0) model

getwd()
## [1] "/home/rstudio"