---
title: "687_Exploratory"
output:
  word_document: default
  html_document: default
  pdf_document: default
---

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


```{r}
library(tidyverse)
dataFile <- "https://intro-datascience.s3.us-east-2.amazonaws.com/Resort01.csv"
originaldata <- read_csv(dataFile)
originaldata$TotalPartySize <- originaldata$Adults + originaldata$Children + originaldata$Babies

# Basic data analysis and/or cleansing
# If all rows have a value, the NA will be 0, and the is.datatype will be 40060
nrow(originaldata[is.na(originaldata$LeadTime),])
nrow(originaldata[is.numeric(originaldata$LeadTime),])

nrow(originaldata[is.na(originaldata$StaysInWeekendNights),])
nrow(originaldata[is.numeric(originaldata$StaysInWeekendNights),])

nrow(originaldata[is.na(originaldata$StaysInWeekNights),])
nrow(originaldata[is.numeric(originaldata$StaysInWeekNights),])

nrow(originaldata[is.na(originaldata$Adults),])
nrow(originaldata[is.numeric(originaldata$Adults),])

nrow(originaldata[is.na(originaldata$Children),])
nrow(originaldata[is.numeric(originaldata$Children),])

nrow(originaldata[is.na(originaldata$Babies),])
nrow(originaldata[is.numeric(originaldata$Babies),])

grouponly <- originaldata[originaldata$MarketSegment == 'Groups',]
min(grouponly$TotalPartySize)
max(grouponly$TotalPartySize)

nrow(originaldata[is.na(originaldata$Meal),])
nrow(originaldata[is.character(originaldata$Meal),])
library(dplyr)
mealsummary <- originaldata %>% group_by(Meal) %>% summarize(count_mealplan = n())

nrow(originaldata[is.na(originaldata$Country),])
nrow(originaldata[is.character(originaldata$Country),])
countrysummary <- originaldata %>% group_by(Country) %>% summarize(count_country = n())
nchar(countrysummary$Country)

nrow(originaldata[is.na(originaldata$MarketSegment),])
nrow(originaldata[is.character(originaldata$MarketSegment),])

marketsummary <- originaldata %>% group_by(MarketSegment) %>% summarize(count_marketsegment = n())

nrow(originaldata[is.na(originaldata$IsRepeatedGuest),])
nrow(originaldata[is.numeric(originaldata$IsRepeatedGuest),])
min(originaldata$IsRepeatedGuest)
max(originaldata$IsRepeatedGuest)

nrow(originaldata[is.na(originaldata$PreviousCancellations),])
nrow(originaldata[is.numeric(originaldata$PreviousCancellations),])
min(originaldata$PreviousCancellations)
max(originaldata$PreviousCancellations)

nrow(originaldata[is.na(originaldata$PreviousBookingsNotCanceled),])
nrow(originaldata[is.numeric(originaldata$PreviousBookingsNotCanceled),])
min(originaldata$PreviousBookingsNotCanceled)
max(originaldata$PreviousBookingsNotCanceled)

nrow(originaldata[is.na(originaldata$ReservedRoomType),])
nrow(originaldata[is.character(originaldata$ReservedRoomType),])
reservedroomsummary <- originaldata %>% group_by(ReservedRoomType) %>% summarize(count_reservedroom = n())

nrow(originaldata[is.na(originaldata$AssignedRoomType),])
nrow(originaldata[is.character(originaldata$AssignedRoomType),])
assignedroomsummary <- originaldata %>% group_by(AssignedRoomType) %>% summarize(count_assignedroom = n())

originaldata$roomWasChanged <- originaldata$ReservedRoomType != originaldata$AssignedRoomType

nrow(originaldata[is.na(originaldata$BookingChanges),])
nrow(originaldata[is.numeric(originaldata$BookingChanges),])
min(originaldata$BookingChanges)
max(originaldata$BookingChanges)

nrow(originaldata[is.na(originaldata$DepositType),])
nrow(originaldata[is.character(originaldata$DepositType),])
depositsummary <- originaldata %>% group_by(DepositType) %>% summarize(count_deposit = n())

nrow(originaldata[is.na(originaldata$CustomerType),])
nrow(originaldata[is.character(originaldata$CustomerType),])
customertypesummary <- originaldata %>% group_by(CustomerType) %>% summarize(count_customer = n())

nrow(originaldata[is.na(originaldata$RequiredCarParkingSpaces),])
nrow(originaldata[is.numeric(originaldata$RequiredCarParkingSpaces),])
min(originaldata$RequiredCarParkingSpaces)
max(originaldata$RequiredCarParkingSpaces)


nrow(originaldata[is.na(originaldata$TotalOfSpecialRequests),])
nrow(originaldata[is.numeric(originaldata$TotalOfSpecialRequests),])
min(originaldata$TotalOfSpecialRequests)
max(originaldata$TotalOfSpecialRequests)

originaldata$TotalDaysStayed <- originaldata$StaysInWeekNights + originaldata$StaysInWeekendNights
min(originaldata$TotalDaysStayed)
max(originaldata$TotalDaysStayed)
nrow(originaldata[originaldata$TotalDaysStayed == 0,])
nrow(originaldata[originaldata$TotalDaysStayed == 0,])

originaldata$LongWeekend <- (originaldata$StaysInWeekNights > 0) & (originaldata$StaysInWeekendNights > 0) & (originaldata$TotalDaysStayed == 3)

originaldata$ExtendedStays <- originaldata$TotalDaysStayed > 8

reportBasicStats <- function(typeofdata, dataset)
{
  return(paste(typeofdata,"has a mean of", sprintf("%0.2f",mean(dataset)),"and a median of",median(dataset),". The range is from",min(dataset),"to",max(dataset)))
}
```

```{r}
# Variable Analysis
# Lead Time
reportBasicStats("Lead Time", originaldata$LeadTime)
hist(originaldata$LeadTime, xlab='Days', main='Lead Time (All bookings)')

reportBasicStats("Lead Time (Cancelled Bookings)", originaldata$LeadTime[originaldata$IsCanceled == 1])
hist(originaldata$LeadTime[originaldata$IsCanceled == 1], xlab='Days', main='Lead Time (Cancelled Bookings)')

reportBasicStats("Lead Time (Successful Bookings)", originaldata$LeadTime[originaldata$IsCanceled == 0])
hist(originaldata$LeadTime[originaldata$IsCanceled == 0], xlab='Days', main='Lead Time (Successful Bookings)')

breaks <- c(0,14,28,42,56,70,84,98,112,126,140,154,168,182,196,210,224,238,252,266,280,294,308,322,336,350,364,737)
# specify interval/bin labels
tags <- c("[0-14)","[14-28)", "[28-42)", "[42-56)", "[56-70)", "[70-84)","[84-98)", "[98-112)","[112-126)", "[126-140)",
          "[140-154)","[154-168)","[168-182)","[182-196)","[196-210)","[210-224)","[224-238)","[238-252)","[252-266)",
          "[266-280)","[280-294)","[294-308)","[308-322)","[322-336)","[336-350)","[350-364)","[364-737)")
# bucketing values into bins
group_successrecords <- cut(originaldata$LeadTime[originaldata$IsCanceled == 0],
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

group_cancelonly <- cut(originaldata$LeadTime[originaldata$IsCanceled == 1], 
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

plot(group_successrecords, col="blue", xlab="Lead Time in 2 week increments", main="Cancel (red) vs Success (blue) based on Lead Time")
plot(group_cancelonly, col="red",add=TRUE)
nrow(originaldata[originaldata$LeadTime < 14,])
nrow(originaldata[originaldata$LeadTime < 14 & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$LeadTime == 0 & originaldata$IsCanceled == 1,])

```

```{r}
# Variable Analysis
# Stays in Weekend Nights
reportBasicStats("Stays in Weekend Nights", originaldata$StaysInWeekendNights)
hist(originaldata$StaysInWeekendNights, xlab='Days', main='Stays in Weekend Nights (All bookings)')

reportBasicStats("Stays in Weekend Nights (Cancelled Bookings)", originaldata$StaysInWeekendNights[originaldata$IsCanceled == 1])
hist(originaldata$StaysInWeekendNights[originaldata$IsCanceled == 1], xlab='Days', main='Stays in Weekend Nights (Cancelled Bookings)')

reportBasicStats("Stays in Weekend Nights (Successful Bookings)", originaldata$StaysInWeekendNights[originaldata$IsCanceled == 0])
hist(originaldata$StaysInWeekendNights[originaldata$IsCanceled == 0], xlab='Days', main='Stays in Weekend Nights (Successful Bookings)')

breaks <- c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
# specify interval/bin labels
tags <- c("[0-1)","[1-2)","[2-3)","[3-4)","[4-5)","[5-6)","[6-7)","[7-8)","[8-9)","[9-10)","[10-11)","[11-12)","[12-13)","[13-14)","[14-15)","[15-16)","[16-17)","[17-18)","[18-19)","[19-20)")
# bucketing values into bins
group_successrecords <- cut(originaldata$StaysInWeekendNights[originaldata$IsCanceled == 0],
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

group_cancelonly <- cut(originaldata$StaysInWeekendNights[originaldata$IsCanceled == 1], 
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

plot(group_successrecords, col="blue", xlab="Stays in Weekend Nights", main="Cancel (red) vs Success (blue) based on Stays in Weekend Nights")
plot(group_cancelonly, col="red",add=TRUE)

```
```{r}
# Variable Analysis
# Stays in Weekday Nights
reportBasicStats("Stays in Weekday Nights", originaldata$StaysInWeekNights)
hist(originaldata$StaysInWeekNights, xlab='Days', main='Stays in Weekday Nights (All bookings)')

reportBasicStats("Stays in Weekday Nights (Cancelled Bookings)", originaldata$StaysInWeekNights[originaldata$IsCanceled == 1])
hist(originaldata$StaysInWeekNights[originaldata$IsCanceled == 1], xlab='Days', main='Stays in Weekday Nights (Cancelled Bookings)')

reportBasicStats("Stays in Weekday Nights (Successful Bookings)", originaldata$StaysInWeekNights[originaldata$IsCanceled == 0])
hist(originaldata$StaysInWeekNights[originaldata$IsCanceled == 0], xlab='Days', main='Stays in Weekday Nights (Successful Bookings)')

breaks <- c(0,5,10,15,20,25,30,35,40,45,50)
# specify interval/bin labels
tags <- c("[0-5)","[5-10)","[10-15)","[15-20)","[20-25)","[25-30)","[30-35)","[35-40)","[40-45)","[45-50)")
# bucketing values into bins
group_successrecords <- cut(originaldata$StaysInWeekNights[originaldata$IsCanceled == 0],
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

group_cancelonly <- cut(originaldata$StaysInWeekNights[originaldata$IsCanceled == 1], 
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

plot(group_successrecords, col="blue", xlab="Stays in Weekday Nights", main="Cancel (red) vs Success (blue) based on Stays in Weekday Nights")
plot(group_cancelonly, col="red",add=TRUE)

```


```{r}
# Variable Analysis
# Total Party Size
reportBasicStats("Total Party Size", originaldata$TotalPartySize)
hist(originaldata$TotalPartySize[originaldata$TotalPartySize < 5], xlab='Days', main='Total Party Size (All bookings of 5 or less)')

reportBasicStats("Total Party Size (Cancelled Bookings)", originaldata$TotalPartySize[originaldata$IsCanceled == 1])
hist(originaldata$TotalPartySize[originaldata$IsCanceled == 1 & originaldata$TotalPartySize < 5], xlab='Days', main='Total Party Size (Cancelled Bookings, 5 or less)')

reportBasicStats("Total Party Size (Successful Bookings)", originaldata$TotalPartySize[originaldata$IsCanceled == 0])
hist(originaldata$TotalPartySize[originaldata$IsCanceled == 0], xlab='Days', main='Total Party Size (Successful Bookings)')

breaks <- c(0,1,2,3,4,5)
# specify interval/bin labels
tags <- c("[0-1)","[1-2)","[2-3)","[3-4)","[4-5)")
# bucketing values into bins
group_successrecords <- cut(originaldata$TotalPartySize[originaldata$IsCanceled == 0 & originaldata$TotalPartySize < 5],
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

group_cancelonly <- cut(originaldata$TotalPartySize[originaldata$IsCanceled == 1 & originaldata$TotalPartySize < 5], 
                  breaks=breaks, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags)

plot(group_successrecords, col="blue", xlab="Stays in Weekday Nights", main="Cancel (red) vs Success (blue) based on Total Party Size")
plot(group_cancelonly, col="red",add=TRUE)

```

```{r}
# Variable Analysis
# Meal Plan
mealsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(Meal) %>% summarize(count_mealplan_success = n())
mealfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(Meal) %>% summarize(count_mealplan_fail = n())
mealtotal <- merge(mealsuccess, mealfail, all=TRUE)
mealtotal$successrate <- (mealtotal$count_mealplan_success / (mealtotal$count_mealplan_success + mealtotal$count_mealplan_fail) * 100)
mealtotal
reportBasicStats("Meal Success Rate", mealtotal$successrate)

barplot(mealtotal$successrate, names.arg=mealtotal$Meal, xlab="Meal Plan", ylab="Success Rate", ylim=(c(0,100)), main="Success rate with Meal Plan")

```


```{r}
# Variable Analysis
# Country

library(rworldmap)

# Find the cancellation rate per country by grouping by country, then dividing cancelled reservations by all reservations for that country
dfSimple_bookings <- originaldata %>% group_by(Country) %>% count()
dfSimple_cancelrate <- originaldata %>% group_by(Country) %>% summarize(mean(IsCanceled))
dfSimple_bookingamount <- originaldata %>% group_by(Country) %>% summarize(sum(TotalPartySize))

# Confirming the math.  PRT shows as 42% in the merged dataframe above, and we see the same value from the calculation below.
dfSimple_merged <- merge(dfSimple_bookings, dfSimple_cancelrate)
nrow(originaldata[originaldata$Country == 'PRT' & originaldata$IsCanceled == 1,]) / nrow(originaldata[originaldata$Country == 'PRT',])

dim(dfSimple_merged)
reportBasicStats("Country Cancellation Rate", dfSimple_merged$`mean(IsCanceled)`)
ccodes <- countrySynonyms

# Cancellation rate map for the entire world
cancelMap <- joinCountryData2Map(dfSimple_merged, joinCode = "ISO3",
  nameJoinColumn = "Country")
mapCountryData(cancelMap, nameColumnToPlot="mean(IsCanceled)", catMethod = "categorical",
  missingCountryCol = gray(.8), colourPalette = c("blue", "red"),addLegend = FALSE, mapTitle="Cancellations Rate By Country (Lowest is blue, Highest is red)")

# Cancellation rate map for the top bookings, get rid of that null country
dfSimple_merged_top20 <- dfSimple_merged[dfSimple_merged$n > 130 & dfSimple_merged$Country != "NULL",]
sum(dfSimple_merged_top20$n)

cancelMapTop20 <- joinCountryData2Map(dfSimple_merged_top20, joinCode = "ISO3",
  nameJoinColumn = "Country")
mapCountryData(cancelMapTop20, nameColumnToPlot="mean(IsCanceled)", catMethod = "categorical",
  missingCountryCol = gray(.8), colourPalette = c("blue", "red"), addLegend = FALSE, mapTitle="Cancellations Rate For Top 20 Countries")



```



```{r}
# Variable Analysis
# Market Segment
marketsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(MarketSegment) %>% summarize(count_market_success = n())
marketfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(MarketSegment) %>% summarize(count_market_fail = n())
markettotal <- merge(marketsuccess, marketfail, all=TRUE)
markettotal$successrate <- (markettotal$count_market_success / (markettotal$count_market_success + markettotal$count_market_fail) * 100)
markettotal
reportBasicStats("Market Segment Rate", markettotal$successrate)

barplot(markettotal$successrate, names.arg=substring(markettotal$MarketSegment,0,7), xlab="Market Segment", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Market Segment")

```

```{r}
# Variable Analysis
# Repeat Guest
repeatsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(IsRepeatedGuest) %>% summarize(count_repeat_success = n())
repeatfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(IsRepeatedGuest) %>% summarize(count_repeat_fail = n())
repeattotal <- merge(repeatsuccess, repeatfail, all=TRUE)
repeattotal$successrate <- (repeattotal$count_repeat_success / (repeattotal$count_repeat_success + repeattotal$count_repeat_fail) * 100)
repeattotal
reportBasicStats("Repeat Guest Rate", repeattotal$successrate)

barplot(repeattotal$successrate, names.arg=c("First Time Guest", "Repeat Guest"), xlab="Repeated Guest", ylab="Success Rate", ylim=(c(0,100)), main="Success rate for Repeated Guests")

```

```{r}

# Variable Analysis
# Previous Cancellations
reportBasicStats("Previous Cancellations", originaldata$PreviousCancellations)
hist(originaldata$PreviousCancellations[originaldata$PreviousCancellations < 5], xlab='Days', main='Previous Cancellations (All bookings)')
nrow(originaldata[originaldata$PreviousCancellations > 0,])
nrow(originaldata[originaldata$PreviousCancellations > 0 & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$PreviousCancellations > 0 & originaldata$IsCanceled == 1,])

```

```{r}

# Variable Analysis
# Previous Bookings Not Cancelled
reportBasicStats("Previous Bookings Not Cancelled", originaldata$PreviousBookingsNotCanceled)
hist(originaldata$PreviousBookingsNotCanceled[originaldata$PreviousBookingsNotCanceled < 5], xlab='Days', main='Previous Not Cancelled (All bookings)')
nrow(originaldata[originaldata$PreviousBookingsNotCanceled > 0,])
nrow(originaldata[originaldata$PreviousBookingsNotCanceled > 0 & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$PreviousBookingsNotCanceled > 0 & originaldata$IsCanceled == 1,])

```


```{r}
# Variable Analysis
# Reserved Room Type
reservedroomsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(ReservedRoomType) %>% summarize(count_reservedroom_success = n())
reservedroomfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(ReservedRoomType) %>% summarize(count_reservedroom_fail = n())
reservedroomtotal <- merge(reservedroomsuccess, reservedroomfail, all=TRUE)
reservedroomtotal$count_reservedroom_success[is.na(reservedroomtotal$count_reservedroom_success)] <- 0
reservedroomtotal$count_reservedroom_fail[is.na(reservedroomtotal$count_reservedroom_fail)] <- 0

reservedroomtotal$successrate <- (reservedroomtotal$count_reservedroom_success / (reservedroomtotal$count_reservedroom_success + reservedroomtotal$count_reservedroom_fail) * 100)
reportBasicStats("Reserved Room Type Rate", reservedroomtotal$successrate)

barplot(reservedroomtotal$successrate, names.arg=reservedroomtotal$ReservedRoomType, xlab="Reserved Room Type", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Reserved Room Type")

reservedroomtotal
```


```{r}
# Variable Analysis
# Assigned Room Type
assignedroomsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(AssignedRoomType) %>% summarize(count_assignedroom_success = n())
assignedroomfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(AssignedRoomType) %>% summarize(count_assignedroom_fail = n())
assignedroomtotal <- merge(assignedroomsuccess, assignedroomfail, all=TRUE)
assignedroomtotal$count_assignedroom_success[is.na(assignedroomtotal$count_assignedroom_success)] <- 0
assignedroomtotal$count_assignedroom_fail[is.na(assignedroomtotal$count_assignedroom_fail)] <- 0

assignedroomtotal$successrate <- (assignedroomtotal$count_assignedroom_success / (assignedroomtotal$count_assignedroom_success + assignedroomtotal$count_assignedroom_fail) * 100)
assignedroomtotal
reportBasicStats("Assigned Room Type Rate", assignedroomtotal$successrate)

barplot(assignedroomtotal$successrate, names.arg=assignedroomtotal$AssignedRoomType, xlab="Assigned Room Type", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Assigned Room Type")

```
```{r}
# Variable Analysis
# Room Was Changed
reportBasicStats("Room Was Changed", originaldata$roomWasChanged)
nrow(originaldata[originaldata$roomWasChanged == 0,])
nrow(originaldata[originaldata$roomWasChanged == 0 & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$roomWasChanged == 0 & originaldata$IsCanceled == 1,])

nrow(originaldata[originaldata$roomWasChanged == 1,])
nrow(originaldata[originaldata$roomWasChanged == 1 & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$roomWasChanged == 1 & originaldata$IsCanceled == 1,])
```

```{r}
# Variable Analysis
# Booking Changes
bookchangesuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(BookingChanges) %>% summarize(count_bookchange_success = n())
bookchangefail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(BookingChanges) %>% summarize(count_bookchange_fail = n())
bookchangetotal <- merge(bookchangesuccess, bookchangefail, all=TRUE)
bookchangetotal$count_bookchange_success[is.na(bookchangetotal$count_bookchange_success)] <- 0
bookchangetotal$count_bookchange_fail[is.na(bookchangetotal$count_bookchange_fail)] <- 0

bookchangetotal$successrate <- (bookchangetotal$count_bookchange_success / (bookchangetotal$count_bookchange_success + bookchangetotal$count_bookchange_fail) * 100)
bookchangetotal
reportBasicStats("Booking Changes Rate", bookchangetotal$successrate)

barplot(bookchangetotal$successrate, names.arg=bookchangetotal$BookingChanges, xlab="Booking Changes", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Booking Changes")


```

```{r}
# Variable Analysis
# Deposit Type
depositsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(DepositType) %>% summarize(count_deposit_success = n())
depositfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(DepositType) %>% summarize(count_deposit_fail = n())
deposittotal <- merge(depositsuccess, depositfail, all=TRUE)
deposittotal$successrate <- (deposittotal$count_deposit_success / (deposittotal$count_deposit_success + deposittotal$count_deposit_fail) * 100)
deposittotal
reportBasicStats("Deposit Type Rate", deposittotal$successrate)

barplot(deposittotal$successrate, names.arg=deposittotal$DepositType, xlab="Deposit Type", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Deposit Type")

```

```{r}
# Variable Analysis
# Customer Type
customertypesuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(CustomerType) %>% summarize(count_customertype_success = n())
customertypefail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(CustomerType) %>% summarize(count_customertype_fail = n())
customertypetotal <- merge(customertypesuccess, customertypefail, all=TRUE)
customertypetotal$successrate <- (customertypetotal$count_customertype_success / (customertypetotal$count_customertype_success + customertypetotal$count_customertype_fail) * 100)
customertypetotal
reportBasicStats("Customer Type Rate", customertypetotal$successrate)

barplot(customertypetotal$successrate, names.arg=customertypetotal$CustomerType, xlab="Customer Type", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Customer Type")

```

```{r}
# Variable Analysis
# Required Parking Spaces
parkingspacessuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(RequiredCarParkingSpaces) %>% summarize(count_parkingspaces_success = n())
parkingspacesfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(RequiredCarParkingSpaces) %>% summarize(count_parkingspaces_fail = n())
parkingspacestotal <- merge(parkingspacessuccess, parkingspacesfail, all=TRUE)
parkingspacestotal$count_parkingspaces_success[is.na(parkingspacestotal$count_parkingspaces_success)] <- 0
parkingspacestotal$count_parkingspaces_fail[is.na(parkingspacestotal$count_parkingspaces_fail)] <- 0

parkingspacestotal$successrate <- (parkingspacestotal$count_parkingspaces_success / (parkingspacestotal$count_parkingspaces_success + parkingspacestotal$count_parkingspaces_fail) * 100)
parkingspacestotal
reportBasicStats("Required Parking Spaces", parkingspacestotal$successrate)

barplot(parkingspacestotal$successrate, names.arg=parkingspacestotal$RequiredCarParkingSpaces, xlab="Required Parking Spaces", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Required Parking Spaces")


```


```{r}
# Variable Analysis
# Number of Special Requests
specialrequestssuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(TotalOfSpecialRequests) %>% summarize(count_specialrequests_success = n())
specialrequestsfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(TotalOfSpecialRequests) %>% summarize(count_specialrequests_fail = n())
specialrequeststotal <- merge(specialrequestssuccess, specialrequestsfail, all=TRUE)
specialrequeststotal$count_specialrequests_success[is.na(specialrequeststotal$count_specialrequests_success)] <- 0
specialrequeststotal$count_specialrequests_fail[is.na(specialrequeststotal$count_specialrequests_fail)] <- 0

specialrequeststotal$successrate <- (specialrequeststotal$count_specialrequests_success / (specialrequeststotal$count_specialrequests_success + specialrequeststotal$count_specialrequests_fail) * 100)
specialrequeststotal
reportBasicStats("Total Special Requests", specialrequeststotal$successrate)

barplot(specialrequeststotal$successrate, names.arg=specialrequeststotal$TotalOfSpecialRequests, xlab="Total Special Requests", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Total Special Requests")


```

```{r}
# Variable Analysis
# Total Days Stayed
totaldaysstayedsuccess <- originaldata[originaldata$IsCanceled == 0,] %>% group_by(TotalDaysStayed) %>% summarize(count_totaldaysstayed_success = n())
totaldaysstayedfail <- originaldata[originaldata$IsCanceled == 1,] %>% group_by(TotalDaysStayed) %>% summarize(count_totaldaysstayed_fail = n())
totaldaysstayedtotal <- merge(totaldaysstayedsuccess, totaldaysstayedfail, all=TRUE)
totaldaysstayedtotal$count_totaldaysstayed_success[is.na(totaldaysstayedtotal$count_totaldaysstayed_success)] <- 0
totaldaysstayedtotal$count_totaldaysstayed_fail[is.na(totaldaysstayedtotal$count_totaldaysstayed_fail)] <- 0

totaldaysstayedtotal$successrate <- (totaldaysstayedtotal$count_totaldaysstayed_success / (totaldaysstayedtotal$count_totaldaysstayed_success + totaldaysstayedtotal$count_totaldaysstayed_fail) * 100)
totaldaysstayedtotal
reportBasicStats("Total Special Requests", totaldaysstayedtotal$successrate)

barplot(totaldaysstayedtotal$successrate, names.arg=totaldaysstayedtotal$TotalDaysStayed, xlab="Total Days Stayed", ylab="Success Rate", ylim=(c(0,100)), main="Success rate by Total Days Stayed")


```


```{r}
# Variable Analysis
# Long Weekends
reportBasicStats("Long Weekends", originaldata$LongWeekend)
nrow(originaldata[originaldata$LongWeekend == FALSE,])
nrow(originaldata[originaldata$LongWeekend == FALSE & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$LongWeekend == FALSE & originaldata$IsCanceled == 1,])

nrow(originaldata[originaldata$LongWeekend == TRUE,])
nrow(originaldata[originaldata$LongWeekend == TRUE & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$LongWeekend == TRUE & originaldata$IsCanceled == 1,])


```

```{r}
# Variable Analysis
# Extended Stays
reportBasicStats("Extended Stays", originaldata$ExtendedStays)
nrow(originaldata[originaldata$ExtendedStays == FALSE,])
nrow(originaldata[originaldata$ExtendedStays == FALSE & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$ExtendedStays == FALSE & originaldata$IsCanceled == 1,])

nrow(originaldata[originaldata$ExtendedStays == TRUE,])
nrow(originaldata[originaldata$ExtendedStays == TRUE & originaldata$IsCanceled == 0,])
nrow(originaldata[originaldata$ExtendedStays == TRUE & originaldata$IsCanceled == 1,])

```


```{r}
# Unsupervised machine learning

library(arules)

bookattempt1 <- originaldata
bookattempt1 <- mutate_if(bookattempt1,is.character, factor)
bookattempt1 <- mutate_if(bookattempt1,is.numeric, factor)
bookattempt1 <- mutate_if(bookattempt1,is.logical, factor)

bookX <- as(bookattempt1, "transactions")
itemFrequency(bookX)
itemFrequencyPlot(bookX, topN=30)

# People who cancelled across all data sets
bookRulesCancelled <- apriori(bookX,
 parameter=list(supp=0.085, conf=0.7),
 control=list(verbose=F),
 appearance=list(default="lhs",rhs=("IsCanceled=1")))

inspect(bookRulesCancelled)
# 34 rules created.
# Most likely to cancel are: Two adults, Portuguese, Room type A assigned, no booking changes, No car required.  71 confidence, 2.5 lift.
# Top common factors: Portuguese, no car spaces, no room change.


bookRulesStayed <- apriori(bookX,
 parameter=list(supp=0.17, conf=0.9),
 control=list(verbose=F),
 appearance=list(default="lhs",rhs=("IsCanceled=0")))

inspect(bookRulesStayed)
# 26 rules created.
# Most likely to stay are: room was changed, no children, no prior cancellations, no deposit with 95 confidence, 1.3 lift.

```
```{r}
portugaldata <- originaldata[originaldata$Country=='PRT',]
portugaldata <- mutate_if(portugaldata,is.character, factor)
portugaldata <- mutate_if(portugaldata,is.numeric, factor)
portugaldata <- mutate_if(portugaldata,is.logical, factor)


portugalX <- as(portugaldata, "transactions")
# Portuguese who cancelled
portRulesCancelled <- apriori(portugalX,
 parameter=list(supp=0.1, conf=0.9),
 control=list(verbose=F),
 appearance=list(default="lhs",rhs=("IsCanceled=1")))

inspect(portRulesCancelled)
# 52 rules created.
# Portuguese most likely to cancel include: Groups, no room change, no parking spaces, no special requests, party size of 2.
# 90 confidence, 2.14 lift.

portRulesStayed <- apriori(portugalX,
 parameter=list(supp=0.13, conf=1),
 control=list(verbose=F),
 appearance=list(default="lhs",rhs=("IsCanceled=0")))

inspect(portRulesStayed)
# 16 rules created.
# Portuguese least likely to cancel include: Parking space needed, no deposit, no prior cancellations.
# 100 confidence, 1.73 lift


```
```{r}
library("kernlab")
library("caret")
# Attempting a SVM based on just lead time
leadcanceltest <- originaldata
leadcanceltest$IsCanceled <- as.factor(leadcanceltest$IsCanceled)
trainList <- createDataPartition(y=leadcanceltest$IsCanceled,p=.70,list=FALSE)
testSet <- leadcanceltest [-trainList,]

trainSet <- leadcanceltest[trainList,]
svmOut <- ksvm(IsCanceled ~ LeadTime, data=trainSet, C = 5, cross = 3, prob.model = TRUE)
svmOut
svmPred <- predict(svmOut,  
                   testSet,
                   type = "response")

str(svmPred)
table(testSet$IsCanceled,svmPred)



diag(table(testSet$IsCanceled,svmPred))
table(testSet$IsCanceled)
confusionMatrix(testSet$IsCanceled, svmPred)
# Accuracy is 0.72% but the no information rate is 98% accurate.  This model is not great.
```
```{r}
# Attempting a SVM based on all variables
alltest <- originaldata
alltest <- mutate_if(alltest,is.character, factor)
alltest <- mutate_if(alltest,is.numeric, factor)
alltest <- mutate_if(alltest,is.logical, factor)

trainList <- createDataPartition(y=alltest$IsCanceled,p=.70,list=FALSE)
testSet <- alltest [-trainList,]

trainSet <- alltest[trainList,]
svmOut <- ksvm(IsCanceled ~ ., data=trainSet, C = 5, cross = 3, prob.model = TRUE)
svmOut
svmPred <- predict(svmOut,  
                   testSet,
                   type = "response")

str(svmPred)
table(testSet$IsCanceled,svmPred)

diag(table(testSet$IsCanceled,svmPred))
table(testSet$IsCanceled)
confusionMatrix(testSet$IsCanceled, svmPred)
# The accuracy rate is 88% while the no information rate is 73%.  This is a better model.


svmOut2 <- ksvm(IsCanceled ~ Country + MarketSegment + IsRepeatedGuest + RequiredCarParkingSpaces, data=trainSet, C = 5, cross = 3, prob.model = TRUE)
svmOut2
svmPred2 <- predict(svmOut2,  
                   testSet,
                   type = "response")
str(svmPred2)
table(testSet$IsCanceled,svmPred2)

diag(table(testSet$IsCanceled,svmPred2))
table(testSet$IsCanceled)
confusionMatrix(testSet$IsCanceled, svmPred2)
# The accuracy rate is 78% with a no information rate of 73%.


```

```{r}
library(e1071)
library(rpart.plot)
allcanceltest <- originaldata
allcanceltest <- mutate_if(allcanceltest,is.character, factor)
allcanceltest <- mutate_if(allcanceltest,is.numeric, factor)
allcanceltest <- mutate_if(allcanceltest,is.logical, factor)

alltrainList <- createDataPartition(y=allcanceltest$IsCanceled,p=.70,list=FALSE)
alltestSet <- allcanceltest [-alltrainList,]

alltrainSet <- allcanceltest[alltrainList,]

trctrl <- trainControl(method="repeatedcv", number=10)
rpart_model <- train(IsCanceled ~ ., method = "rpart",data = alltrainSet, trControl=trctrl, tuneLength = 50)
rpart.plot(rpart_model$finalModel)
rplotPred <- predict(rpart_model, newdata=alltestSet)
confusionMatrix(alltestSet$IsCanceled, rplotPred)
varImp(rpart_model)
# 85% accuracy.  No information rate of 75%.  
# Top factors: Required Parking Spaces, room change, was country Portugal, Non refundable deposit

# Just look at Portugal
portugaltest <- originaldata[originaldata$Country == 'PRT',-9]
portugaltest <- mutate_if(portugaltest,is.character, factor)
portugaltest <- mutate_if(portugaltest,is.numeric, factor)
portugaltest <- mutate_if(portugaltest,is.logical, factor)

alltrainList <- createDataPartition(y=portugaltest$IsCanceled,p=.70,list=FALSE)
alltestSet <- portugaltest [-alltrainList,]

alltrainSet <- portugaltest[alltrainList,]

trctrl <- trainControl(method="repeatedcv", number=10)
rpart_model <- train(IsCanceled ~ ., method = "rpart",data = alltrainSet, trControl=trctrl, tuneLength = 50)
rpart.plot(rpart_model$finalModel)
rplotPred <- predict(rpart_model, newdata=alltestSet)
confusionMatrix(alltestSet$IsCanceled, rplotPred)
varImp(rpart_model)
# 83% accuracy, no info rate is 58%
# Top factors: Required car parking spaces, total days 1, room changed, market segment direct, non refundable deposit

# Trim down variables
trctrl <- trainControl(method="repeatedcv", number=10)
rpart_model <- train(IsCanceled ~ RequiredCarParkingSpaces + TotalDaysStayed + roomWasChanged + DepositType + MarketSegment, method = "rpart",data = alltrainSet, trControl=trctrl, tuneLength = 50)
rpart.plot(rpart_model$finalModel)
rplotPred <- predict(rpart_model, newdata=alltestSet)
confusionMatrix(alltestSet$IsCanceled, rplotPred)
varImp(rpart_model)
# 78% accuracy, no info rate is 53%
# Top factors: Required car parking spaces, room changed, market segment direct, market segment groups, non refundable deposit

# One final model for Portugal with what we assume to be the three most significant variables.
trctrl <- trainControl(method="repeatedcv", number=10)
rpart_model <- train(IsCanceled ~ RequiredCarParkingSpaces + roomWasChanged + DepositType, method = "rpart",data = alltrainSet, trControl=trctrl, tuneLength = 50)
rpart.plot(rpart_model$finalModel)
rplotPred <- predict(rpart_model, newdata=alltestSet)
confusionMatrix(alltestSet$IsCanceled, rplotPred)
varImp(rpart_model)
# 78% accuracy, no info rate is 53%
# Top factors: Required car parking spaces, room changed, market segment direct, market segment groups, non refundable deposit

```
```{r}
#data cleaning:
  
#1.leadtime  
df <- originaldata
hist(df$LeadTime) 
summary(df$LeadTime)
#barplot
ggplot(df)+aes(x=df$LeadTime,fill=df$IsCanceled)+geom_bar()
#boxplot
ggplot(df)+aes(y=df$LeadTime)+geom_boxplot()#leadtime more than 350 are outliners
#scartter plot
ggplot(df)+aes(y=df$LeadTime,x=df$StaysInWeekendNights+df$StaysInWeekNights,fill=df$IsCanceled)+geom_point()+geom_smooth(method="lm", se=FALSE)
#relationship with leadtime and no of days to stay



#2.stay's in weekend and weekdays
hist(df$StaysInWeekendNights)
hist(df$StaysInWeekNights)
ggplot(df)+aes(x=df$StaysInWeekendNights+df$StaysInWeekNights,fill=df$IsCanceled)+geom_bar()

#Analysis Part-2: dividing the data into weekdays,weekends,long-holiday,no-stay

#df$StaysInWeekendNights>0 & df$StaysInWeekNights==0 #weekends
#df$StaysInWeekendNights==0 & df$StaysInWeekNights>0 #weekdays
#df$StaysInWeekendNights>0 & df$StaysInWeekNights>0  #longholiday
#df$StaysInWeekendNights==0 & df$StaysInWeekNights==0 #no-stay


(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights==0,])/nrow(df))*100    
# weekEnds = 2298 , 5.73% of people book for weekends
(nrow(df[df$StaysInWeekendNights==0 & df$StaysInWeekNights>0,])/nrow(df))*100    
# weekDays = 13797 , 34.44% people are booking for weekdays
(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights>0,])/nrow(df))*100     
# longHoliday =23581 , 58.86% people are booking for longHoliday
(nrow(df[df$StaysInWeekendNights==0 & df$StaysInWeekNights==0,])/nrow(df))*100   
# noStay   = 384 , 0.95% people who book don't stay in hotel at nights


#cancelRates for individual group

(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights==0 & df$IsCanceled ==1 ,])/nrow(df))*100
(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights==0 & df$IsCanceled ==1 ,])/nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights==0,]))*100
# weekEnd: 421/2298 people are canceling their reservation, which is 1.05% of whole reservations of the hotel, 18.32% of people who book for weekEnd are cancelling

(nrow(df[df$StaysInWeekendNights==0 & df$StaysInWeekNights>0 & df$IsCanceled ==1,])/nrow(df))*100
(nrow(df[df$StaysInWeekendNights==0 & df$StaysInWeekNights>0 & df$IsCanceled ==1,])/nrow(df[df$StaysInWeekendNights==0 & df$StaysInWeekNights>0,]))*100
# weekDays: 3233/13797 are canceling their reservations, which is 8.07% of whole reservations of the hotel, 23.43% of people who book for weekDays are cancelling

(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights>0 & df$IsCanceled ==1,])/nrow(df))*100
(nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights>0 & df$IsCanceled ==1,])/nrow(df[df$StaysInWeekendNights>0 & df$StaysInWeekNights>0,]))*100
# longHoliday: 7456/23581 are canceling their reservations, which is 18.61% of whole reservations of the hotel, 31.61% of people who book for longHolidays are cancelling

bin1<-df[df$StaysInWeekendNights>0 & df$StaysInWeekNights==0,]
bin1$totalDays<-bin1$StaysInWeekendNights+bin1$StaysInWeekNights
bin2<-df[df$StaysInWeekendNights==0 & df$StaysInWeekNights>0,]
bin2$totalDays<-bin2$StaysInWeekendNights+bin2$StaysInWeekNights
bin3<-df[df$StaysInWeekendNights>0 & df$StaysInWeekNights>0,]
bin3$totalDays<-bin3$StaysInWeekendNights+bin3$StaysInWeekNights
bin4<-df[df$StaysInWeekendNights==0 & df$StaysInWeekNights==0,]
bin4$totalDays<-bin4$StaysInWeekendNights+bin4$StaysInWeekNights

ggplot(bin1)+aes(x=bin1$StaysInWeekendNights+bin1$StaysInWeekNights,fill=bin1$IsCanceled)+geom_bar()#weekend
ggplot(bin2)+aes(x=bin2$StaysInWeekendNights+bin2$StaysInWeekNights,fill=bin2$IsCanceled)+geom_bar()#weekdays
ggplot(bin3)+aes(x=bin3$StaysInWeekendNights+bin3$StaysInWeekNights,fill=bin3$IsCanceled)+geom_bar()#longholidays
ggplot(bin4)+aes(x=bin4$StaysInWeekendNights+bin4$StaysInWeekNights,fill=bin4$IsCanceled)+geom_bar()#nostay


# so if we can find te patterns for weekDay cancellations and longHoliday cancellations





#adults,children and babies
ggplot(df)+aes(x=df$Adults,y=df$Children+df$Babies,color=df$IsCanceled)+geom_point()+geom_smooth(method="lm", se=FALSE)
ggplot(df)+aes(x=df$Adults,y=df$StaysInWeekendNights+df$StaysInWeekNights,color=df$IsCanceled)+geom_point()+geom_smooth(method="lm", se=FALSE)
ggplot(df)+aes(x=df$Children+df$Babies,y=df$StaysInWeekendNights+df$StaysInWeekNights,color=df$IsCanceled)+geom_point()+geom_smooth(method="lm", se=FALSE)

```


```{r}
library(tidyverse)
original_data<-read_csv("https://intro-datascience.s3.us-east-2.amazonaws.com/Resort01.csv")
original_data<-original_data[(original_data$Country=="AUT"|original_data$Country=="BEL"|original_data$Country=="BRA"|original_data$Country=="CHE"|original_data$Country=="CN"|
                             original_data$Country=="DEU"|original_data$Country=="ESP"|original_data$Country=="FRA"|original_data$Country=="GBR"|original_data$Country=="IRL"|
                             original_data$Country=="ITA"|original_data$Country=="NLD"|original_data$Country=="POL"|original_data$Country=="PRT"|original_data$Country=="ROU"|
                               original_data$Country=="RUS"|original_data$Country=="SWE"|original_data$Country=="USA"|original_data$Country=="FIN"|original_data$Country=="NOR"|
                               original_data$Country=="CHN"|original_data$Country=="AUT"),]



```


```{r}
#df is as per document
#df1 is given data that is not changed
country_count<-original_data%>%group_by(Country)%>%count(Country)
country_analysis1<-original_data%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
country_analysis1<-merge(country_count,country_analysis1,by="Country")
names(country_analysis1)[names(country_analysis1) == 'n'] <- 'no_of_bookings'
names(country_analysis1)[names(country_analysis1) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
country_analysis1<-country_analysis1[order(-country_analysis1$no_of_bookings),]
country_analysis1<-country_analysis1[country_analysis1$no_of_bookings>100,]
ggplot(country_analysis1)+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
#longholiday and weekdays
longHoliday<-original_data[original_data$StaysInWeekendNights>0 & original_data$StaysInWeekNights>0,]
weekDays<-original_data[original_data$StaysInWeekendNights==0 & original_data$StaysInWeekNights>0,]













```


```{r}
#longholiday
lh_country_count<-longHoliday%>%group_by(Country)%>%count(Country)
lh_country_C<-longHoliday%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
lh_country_analysis<-merge(lh_country_count,lh_country_C,by="Country")
names(lh_country_analysis)[names(lh_country_analysis) == 'n'] <- 'no_of_bookings'
names(lh_country_analysis)[names(lh_country_analysis) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
lh_country_analysis$cancellation_rate<-lh_country_analysis$cancellation_rate*100
lh_country_analysis<-lh_country_analysis[order(-lh_country_analysis$no_of_bookings),]
lh_country_analysis<-lh_country_analysis[lh_country_analysis$no_of_bookings>100,]
ggplot(lh_country_analysis[lh_country_analysis$no_of_bookings>=100,])+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
#weekday
wd_country_count<-weekDays%>%group_by(Country)%>%count(Country)
wd_country_C<-weekDays%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
wd_country_analysis<-merge(lh_country_count,lh_country_C,by="Country")
names(wd_country_analysis)[names(wd_country_analysis) == 'n'] <- 'no_of_bookings'
names(wd_country_analysis)[names(wd_country_analysis) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
wd_country_analysis<-wd_country_analysis[order(-wd_country_analysis$no_of_bookings),]
wd_country_analysis<-wd_country_analysis[wd_country_analysis$no_of_bookings>100,]
ggplot(wd_country_analysis)+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
library(arules)
library(arulesViz)
#str(longHoliday)
#longHoliday$IsCanceled<-as.factor(longHoliday$IsCanceled)
#lh_apriori<-as(longHoliday,"transactions")
#ruleset_cancellations<- apriori(lh_apriori,parameter=list(supp=0.125, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=1")))
#inspect(ruleset_cancellations)
#ruleset_stayed<- apriori(lh_apriori,parameter=list(supp=0.6, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=0")))
#inspectDT(ruleset_stayed)


```


```{r}
library(arules)
library(arulesViz)
#str(longHoliday)
#view(weekDays)
#weekDays$IsCanceled<-as.factor(weekDays$IsCanceled)
#discretizeDF(weekDays[,c(-3)], methods = NULL, default = NULL)
#wd_apriori<-as(weekDays[,c(-3)],"transactions")
#ruleset_cancellations1<- apriori(wd_apriori,parameter=list(supp=0.112, conf=0.5),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=1")))
#inspect(ruleset_cancellations1)
#ruleset_stayed1<- apriori(wd_apriori,parameter=list(supp=0.6, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=0")))
#inspect(ruleset_stayed1)
```


```{r}
view(longHoliday)
longHoliday$total_days_stayed<-longHoliday$StaysInWeekendNights+longHoliday$StaysInWeekNights
longHoliday$withChildren<-ifelse(longHoliday$Children==0&longHoliday$Babies==0,0,1)
```


```{r}
lhs<-longHoliday%>%group_by(Meal)%>%count()
#longHoliday$IsCanceled<-as.character(longHoliday$IsCanceled)
rhs<-longHoliday%>%group_by(Meal)%>%summarize(mean(IsCanceled))

longHoliday_meal<-merge(lhs,rhs,by="Meal")
names(longHoliday_meal)[names(longHoliday_meal) == 'n'] <- 'no_of_bookings'
names(longHoliday_meal)[names(longHoliday_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
longHoliday_meal$no_of_cancellations<-longHoliday_meal$no_of_bookings*longHoliday_meal$cancellation_rate
ggplot(longHoliday_meal)+aes(x=Meal,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')
ggplot(longHoliday_meal)+aes(x=Meal,y=no_of_bookings,fill=no_of_cancellations)+geom_bar(stat='identity')
```


```{r}
lhs<-weekDays%>%group_by(Meal)%>%count()
#longHoliday$IsCanceled<-as.character(longHoliday$IsCanceled)
rhs<-weekDays%>%group_by(Meal)%>%summarize(mean(IsCanceled))

weekDay_meal<-merge(lhs,rhs,by="Meal")
names(weekDay_meal)[names(weekDay_meal) == 'n'] <- 'no_of_bookings'
names(weekDay_meal)[names(weekDay_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
weekDay_meal$no_of_cancellations<-weekDay_meal$no_of_bookings*weekDay_meal$cancellation_rate
ggplot(weekDay_meal)+aes(x=Meal,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')
ggplot(weekDay_meal)+aes(x=Meal,y=no_of_bookings,fill=no_of_cancellations)+geom_bar(stat='identity')







```


```{r}
lhs<-weekDays%>%group_by(DepositType,CustomerType,Meal)%>%count()
rhs<-weekDays%>%group_by(DepositType,CustomerType,Meal)%>%summarize(mean(IsCanceled))
wd_dt_ct_meal<-merge(lhs,rhs,by.x=c("DepositType","CustomerType","Meal"),by.y=c("DepositType","CustomerType","Meal"))
names(wd_dt_ct_meal)[names(wd_dt_ct_meal) == 'n'] <- 'no_of_bookings'
names(wd_dt_ct_meal)[names(wd_dt_ct_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
wd_dt_ct_meal


lhs<-weekDays%>%group_by(DepositType,CustomerType)%>%count()
rhs<-weekDays%>%group_by(DepositType,CustomerType)%>%summarize(mean(IsCanceled))
wd_dt_ct<-merge(lhs,rhs,by.x=c("DepositType","CustomerType"),by.y=c("DepositType","CustomerType"))
names(wd_dt_ct)[names(wd_dt_ct) == 'n'] <- 'no_of_bookings'
names(wd_dt_ct)[names(wd_dt_ct) == 'mean(IsCanceled)'] <- 'cancellation_rate'
wd_dt_ct
wd_dt_ct[order(wd_dt_ct$CustomerType),]
wd_dt_ct_meal[order(wd_dt_ct_meal$Meal,wd_dt_ct_meal$CustomerType),]

```


```{r}
lhs<-longHoliday%>%group_by(Country,DepositType)%>%count()
rhs<-longHoliday%>%group_by(Country,DepositType)%>%summarize(mean(IsCanceled))
lh_country_dt<-merge(lhs,rhs,by.x=c("Country","DepositType"),by.y=c("Country","DepositType"))
names(lh_country_dt)[names(lh_country_dt) == 'n'] <- 'no_of_bookings'
names(lh_country_dt)[names(lh_country_dt) == 'mean(IsCanceled)'] <- 'cancellation_rate'
lh_country_dt[lh_country_dt$no_of_bookings>100,]

ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$DepositType)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$cancellation_rate,shape=lh_country_dt$DepositType)+geom_point(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))+geom_smooth(method="lm", se=FALSE)


```


```{r}
library(tidyverse)
original_data<-read_csv("https://intro-datascience.s3.us-east-2.amazonaws.com/Resort01.csv")
original_data<-original_data[(original_data$Country=="AUT"|original_data$Country=="BEL"|original_data$Country=="BRA"|original_data$Country=="CHE"|original_data$Country=="CN"|
                             original_data$Country=="DEU"|original_data$Country=="ESP"|original_data$Country=="FRA"|original_data$Country=="GBR"|original_data$Country=="IRL"|
                             original_data$Country=="ITA"|original_data$Country=="NLD"|original_data$Country=="POL"|original_data$Country=="PRT"|original_data$Country=="ROU"|
                               original_data$Country=="RUS"|original_data$Country=="SWE"|original_data$Country=="USA"|original_data$Country=="FIN"|original_data$Country=="NOR"|
                               original_data$Country=="CHN"|original_data$Country=="AUT"),]



```


```{r}
#df is as per document
#df1 is given data that is not changed
country_count<-original_data%>%group_by(Country)%>%count(Country)
country_analysis1<-original_data%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
country_analysis1<-merge(country_count,country_analysis1,by="Country")
names(country_analysis1)[names(country_analysis1) == 'n'] <- 'no_of_bookings'
names(country_analysis1)[names(country_analysis1) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
country_analysis1<-country_analysis1[order(-country_analysis1$no_of_bookings),]
country_analysis1<-country_analysis1[country_analysis1$no_of_bookings>100,]
ggplot(country_analysis1)+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
#longholiday and weekdays
longHoliday<-original_data[original_data$StaysInWeekendNights>0 & original_data$StaysInWeekNights>0,]
weekDays<-original_data[original_data$StaysInWeekendNights==0 & original_data$StaysInWeekNights>0,]













```


```{r}
#longholiday
lh_country_count<-longHoliday%>%group_by(Country)%>%count(Country)
lh_country_C<-longHoliday%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
lh_country_analysis<-merge(lh_country_count,lh_country_C,by="Country")
names(lh_country_analysis)[names(lh_country_analysis) == 'n'] <- 'no_of_bookings'
names(lh_country_analysis)[names(lh_country_analysis) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
lh_country_analysis$cancellation_rate<-lh_country_analysis$cancellation_rate*100
lh_country_analysis<-lh_country_analysis[order(-lh_country_analysis$no_of_bookings),]
lh_country_analysis<-lh_country_analysis[lh_country_analysis$no_of_bookings>100,]
ggplot(lh_country_analysis[lh_country_analysis$no_of_bookings>=100,])+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
#weekday
wd_country_count<-weekDays%>%group_by(Country)%>%count(Country)
wd_country_C<-weekDays%>%group_by(Country)%>%summarize(mean(as.numeric(IsCanceled)))
wd_country_analysis<-merge(lh_country_count,lh_country_C,by="Country")
names(wd_country_analysis)[names(wd_country_analysis) == 'n'] <- 'no_of_bookings'
names(wd_country_analysis)[names(wd_country_analysis) == 'mean(as.numeric(IsCanceled))'] <- 'cancellation_rate'
wd_country_analysis<-wd_country_analysis[order(-wd_country_analysis$no_of_bookings),]
wd_country_analysis<-wd_country_analysis[wd_country_analysis$no_of_bookings>100,]
ggplot(wd_country_analysis)+aes(x=Country,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
```


```{r}
library(arules)
library(arulesViz)
#str(longHoliday)
#longHoliday$IsCanceled<-as.factor(longHoliday$IsCanceled)
#lh_apriori<-as(longHoliday,"transactions")
#ruleset_cancellations<- apriori(lh_apriori,parameter=list(supp=0.125, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=1")))
#inspect(ruleset_cancellations)
#ruleset_stayed<- apriori(lh_apriori,parameter=list(supp=0.6, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=0")))
#inspectDT(ruleset_stayed)


```


```{r}
library(arules)
library(arulesViz)
#str(longHoliday)
#view(weekDays)
#weekDays$IsCanceled<-as.factor(weekDays$IsCanceled)
#discretizeDF(weekDays[,c(-3)], methods = NULL, default = NULL)
#wd_apriori<-as(weekDays[,c(-3)],"transactions")
#ruleset_cancellations1<- apriori(wd_apriori,parameter=list(supp=0.112, conf=0.5),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=1")))
#inspect(ruleset_cancellations1)
#ruleset_stayed1<- apriori(wd_apriori,parameter=list(supp=0.6, conf=0.7),control=list(verbose=F),appearance=list(default="lhs",rhs=("IsCanceled=0")))
#inspect(ruleset_stayed1)
```


```{r}
view(longHoliday)
longHoliday$total_days_stayed<-longHoliday$StaysInWeekendNights+longHoliday$StaysInWeekNights
longHoliday$withChildren<-ifelse(longHoliday$Children==0&longHoliday$Babies==0,0,1)
```


```{r}
lhs<-longHoliday%>%group_by(Meal)%>%count()
#longHoliday$IsCanceled<-as.character(longHoliday$IsCanceled)
rhs<-longHoliday%>%group_by(Meal)%>%summarize(mean(IsCanceled))

longHoliday_meal<-merge(lhs,rhs,by="Meal")
names(longHoliday_meal)[names(longHoliday_meal) == 'n'] <- 'no_of_bookings'
names(longHoliday_meal)[names(longHoliday_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
longHoliday_meal$no_of_cancellations<-longHoliday_meal$no_of_bookings*longHoliday_meal$cancellation_rate
ggplot(longHoliday_meal)+aes(x=Meal,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')
ggplot(longHoliday_meal)+aes(x=Meal,y=no_of_bookings,fill=no_of_cancellations)+geom_bar(stat='identity')
```


```{r}
lhs<-weekDays%>%group_by(Meal)%>%count()
#longHoliday$IsCanceled<-as.character(longHoliday$IsCanceled)
rhs<-weekDays%>%group_by(Meal)%>%summarize(mean(IsCanceled))

weekDay_meal<-merge(lhs,rhs,by="Meal")
names(weekDay_meal)[names(weekDay_meal) == 'n'] <- 'no_of_bookings'
names(weekDay_meal)[names(weekDay_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
weekDay_meal$no_of_cancellations<-weekDay_meal$no_of_bookings*weekDay_meal$cancellation_rate
ggplot(weekDay_meal)+aes(x=Meal,y=no_of_bookings,fill=cancellation_rate)+geom_bar(stat='identity')
ggplot(weekDay_meal)+aes(x=Meal,y=no_of_bookings,fill=no_of_cancellations)+geom_bar(stat='identity')







```


```{r}
lhs<-weekDays%>%group_by(DepositType,CustomerType,Meal)%>%count()
rhs<-weekDays%>%group_by(DepositType,CustomerType,Meal)%>%summarize(mean(IsCanceled))
wd_dt_ct_meal<-merge(lhs,rhs,by.x=c("DepositType","CustomerType","Meal"),by.y=c("DepositType","CustomerType","Meal"))
names(wd_dt_ct_meal)[names(wd_dt_ct_meal) == 'n'] <- 'no_of_bookings'
names(wd_dt_ct_meal)[names(wd_dt_ct_meal) == 'mean(IsCanceled)'] <- 'cancellation_rate'
wd_dt_ct_meal


lhs<-weekDays%>%group_by(DepositType,CustomerType)%>%count()
rhs<-weekDays%>%group_by(DepositType,CustomerType)%>%summarize(mean(IsCanceled))
wd_dt_ct<-merge(lhs,rhs,by.x=c("DepositType","CustomerType"),by.y=c("DepositType","CustomerType"))
names(wd_dt_ct)[names(wd_dt_ct) == 'n'] <- 'no_of_bookings'
names(wd_dt_ct)[names(wd_dt_ct) == 'mean(IsCanceled)'] <- 'cancellation_rate'
wd_dt_ct
wd_dt_ct[order(wd_dt_ct$CustomerType),]
wd_dt_ct_meal[order(wd_dt_ct_meal$Meal,wd_dt_ct_meal$CustomerType),]

```


```{r}
lhs<-longHoliday%>%group_by(Country,DepositType)%>%count()
rhs<-longHoliday%>%group_by(Country,DepositType)%>%summarize(mean(IsCanceled))
lh_country_dt<-merge(lhs,rhs,by.x=c("Country","DepositType"),by.y=c("Country","DepositType"))
names(lh_country_dt)[names(lh_country_dt) == 'n'] <- 'no_of_bookings'
names(lh_country_dt)[names(lh_country_dt) == 'mean(IsCanceled)'] <- 'cancellation_rate'
lh_country_dt[lh_country_dt$no_of_bookings>100,]

ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$cancellation_rate)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$DepositType)+geom_bar(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))
ggplot(lh_country_dt)+aes(x=lh_country_dt$Country,y=lh_country_dt$no_of_bookings,fill=lh_country_dt$cancellation_rate,shape=lh_country_dt$DepositType)+geom_point(stat='identity')+theme(axis.text.x = element_text(angle = 90,hjust = 1))+geom_smooth(method="lm", se=FALSE)


```
