R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

library —————————————————————–

#khai báo thư viện library(“flagr”) library(“reshape2”) library(“utils”) library(“readxl”) #đọc excel

#khai báo thư viện của ggplot2 library(ggplot2) library(tidyverse) library(ggthemes)

#chorddiag #install.packages(“chorddiag”) #install.packages(“devtools”) #devtools::install_github(“mattflor/chorddiag”, build_vignettes = TRUE) #library(chorddiag)

#mặc định library(“reshape2”) library(“knitr”) # tạo bảng library(“grid”) library(“gridExtra”) # vẽ nhiều đồ thị cùng lúc library(“kableExtra”) # tạo bảng library(“naniar”) # cho dữ liệu missing library(“mice”) # điền các giá trị missing library(“rmarkdown”)

bar chart race

library(“gganimate”) #library(“ggflags”) library(“countrycode”) library(knitr)

#sửa dữ liệu date library(lubridate) library(stringr) # world map library(“maps”) library(“geosphere”)

BTL ———————————————————————

t = file.choose() aa <- read.csv(t) view(aa) y = file.choose() bb <- read.csv(y) view(bb) var(na.omit(aa)) attach(aa) names(aa) names(bb) glimpse(aa) #xem tổng quan dữ liệu glimpse(bb) dim(aa) # missing —————————————————————– library(“naniar”) # cho dữ liệu missing library(“mice”) # điền các giá trị missing. gg_miss_var(aa) # vẽ biểu đồ dữ liệu khuyết sum(is.na(aa)) #đếm số dữ liệu bị khuyết

liệt kê những dòng có dữ liệu bị mất ————————————

mis <- aa[!complete.cases(aa), ] view(mis)

sửa dữ liệu date cho missing ——————————————————–

library(lubridate) date <- as.Date(parse_date_time(aa\(date, c("ymd","mdy"))) date date1 <- data.frame(date) aa\)date <- date1$date #cột date của file gốc được sửa glimpse(aa)

Sửa dữ liệu season ————————————

df <- data.frame(c(aa\(season)) df\)MONTH<-month(aa\(date) df\)DAY<-mday(aa\(date) df\)DAY_PLUS_MONTH<-df\(DAY+df\)MONTH*100 df <- df %>% mutate(SEASON = case_when( DAY_PLUS_MONTH %in% 301:530 ~ ‘Autumn’, DAY_PLUS_MONTH %in% 601:831 ~ ‘Winter’, DAY_PLUS_MONTH %in% 901:1130 ~ ‘Spring’, TRUE ~ ‘Summer’)) view(df) aa\(season <- df\)SEASON view(aa)

sửa dữ liệu date cho dirty ——————————————————–

library(lubridate) date2 <- as.Date(parse_date_time(bb\(date, c("ymd","mdy"))) date2 date3 <- data.frame(date2) bb\)date <- date3$date2 #cột date của file gốc được sửa glimpse(bb)

Tính toán lại order_price và order_total ——————————————————–

price <- aa %>% rowwise %>% mutate(order_price = if_else(is.na(order_price), (order_total - delivery_charges)/((1)-coupon_discount/(100)), order_price)) %>% mutate(order_total = if_else(is.na(order_total), (order_price)*((1)-coupon_discount/(100))+delivery_charges, order_total)) %>% view()

price\(is_happy_customer <- as.logical(price\)is_happy_customer) glimpse(price) gg_miss_var(aa) # vẽ biểu đồ dữ liệu khuyết

Dùng mice để điền giá trị thiếu

data.imp <- mice(price, maxit=10, seed = 12345, print=FALSE) data.imp1 <-complete(data.imp, 3) data.imp #show imputation method data.imp1 str(data.imp1)

Điền dữ liệu khuyết ——————————————————–

as.data.frame(data.imp1) # order_total price\(order_total <- ifelse(is.na(price\)order_total), data.imp1\(order_total,price\)order_total) aa\(order_total <- price\)order_total # order_price price\(order_price <- ifelse(is.na(price\)order_price), data.imp1\(order_price,price\)order_price) aa\(order_price <- price\)order_price # distance_to_nearest_warehouse aa\(distance_to_nearest_warehouse[is.na(aa\)distance_to_nearest_warehouse)]=mean(aa\(distance_to_nearest_warehouse,na.rm = T) # customer_lat aa\)customer_lat[is.na(aa\(customer_lat)]=mean(aa\)customer_lat,na.rm = T) #customer_long aa\(customer_long[is.na(aa\)customer_long)]=mean(aa$customer_long,na.rm = T)

gg_miss_var(aa) # vẽ biểu đồ dữ liệu khuyết

tính toán distance_to_nearest_warehouse ——————————————————–

khachhang <- bb %>% select(customer_lat,customer_long) dist <- khachhang %>% rowwise() %>% mutate(new = map(list(c(customer_long, customer_lat)), ~ warehouses %>% rowwise() %>% mutate(dist = distGeo((c(lon, lat)), .x)) %>% ungroup %>% filter(dist == min(dist)) %>% select(names, dist))) %>% ungroup() %>% unnest_wider(new) %>% as_tibble() %>% print(n=500) %>% as.data.frame() as.data.frame(dist) #view(dist) #view the result compare = data.frame(order_id=c(bb\(order_id), nearest=c(bb\)nearest_warehouse), nearest_fix=c(dist\(names), distance_Cal=c(round(dist\)dist/(1000),4)),distance=c(bb\(distance_to_nearest_warehouse)) view(compare) compare\)result=ifelse(compare\(nearest == compare\)nearest_fix, ‘Same’, ‘NotSame’) view(compare) #compare it with the bb compare_notsame <- compare %>% filter(result %in% c(“NotSame”)) view(compare_notsame) #compare the different in the nearest_Warehouse

#Some distance is abnormal compare to other, so make thier latitude \(customer_lat <- abs(xstk\)customer_lat) bb\(customer_lat = bb\)customer_lat*(-1) view(bb)

sửa dữ liệu warehouse (dirty) —————————————————

bb\(nearest_warehouse[bb\)nearest_warehouse == “thompson”] <- “Thompson” bb\(nearest_warehouse[bb\)nearest_warehouse == “bakers”] <- “Bakers” bb\(nearest_warehouse[bb\)nearest_warehouse == “nickolson”] <- “Nickolson” unique(bb$nearest_warehouse) glimpse(bb)

sửa dữ liệu season (dirty) ———————————————-

bb\(season[bb\)season == “winter”] <- “Winter” bb\(season[bb\)season == “summer”] <- “Summer” bb\(season[bb\)season == “autumn”] <- “Autumn” bb\(season[bb\)season == “spring”] <- “Spring” unique(bb$season)

sửa season không khớp với thời gian được cho (dirty) ——————–

df <- data.frame(c(bb\(season)) df\)MONTH<-month(bb\(date) df\)DAY<-mday(bb\(date) df\)DAY_PLUS_MONTH<-df\(DAY+df\)MONTH*100 df <- df %>% mutate(SEASON = case_when( DAY_PLUS_MONTH %in% 301:530 ~ ‘Autumn’, DAY_PLUS_MONTH %in% 601:831 ~ ‘Winter’, DAY_PLUS_MONTH %in% 901:1130 ~ ‘Spring’, TRUE ~ ‘Summer’)) view(df) bb\(season <- df\)SEASON

tính toán lại khoảng cách tới nearest_warehouse ————————-

custom <- aa %>% select(customer_lat,customer_long) u = file.choose() warehouses <- read_csv(u) custom1 <- custom %>% rowwise() %>% mutate(new = map(list(c(customer_long, customer_lat)), ~ warehouses %>% rowwise() %>% mutate(dist = distGeo((c(lon, lat)), .x)) %>% ungroup %>% filter(dist == min(dist)) %>% select(names, dist))) %>% ungroup() %>% unnest_wider(new) %>% as_tibble() %>% print(n=500) %>% as.data.frame()

loại bỏ biến ngoại lai ————————————————–

Q1_order_total = data.frame(Q1=quantile(aa\(order_total, probs = 0.25)) Q1_order_total # Q1 của khoảng tứ phân vị Q3_order_total = data.frame(Q3=quantile(aa\)order_total, probs = 0.75)) Q3_order_total # Q3 của khoảng tứ phân vị Lower_limit <- Q1_order_total\(Q1 - 1.5*IQR(aa\)order_total) Lower_limit Upper_limit <- Q3_order_total\(Q3 + 1.5*IQR(aa\)order_total) Upper_limit Outlier = data.frame(order_total=c(aa\(order_total)) Outlier\)result = if_else(between(aa\(order_total, Lower_limit, Upper_limit), 'NotOutlier', 'Outlier' ) aa\)result = Outlier$result view(aa) View(Outlier) # kiểm tra biến ngoại lai Outlier1 <-Outlier %>% filter(result %in% c(‘Outlier’)) view(Outlier1)

aa_nooutlier <- aa[aa$result == ‘NotOutlier’,] view(aa_nooutlier) aa_final <- aa_nooutlier[, -which(names(aa_nooutlier) == “result”)] glimpse(aa_final) view(aa_final) dirtydata_final <- aa_final

xuất file đã xử lý ——————————————————

install.packages(“writexl”) library(writexl) write.csv(aa, “missingfinal.csv”) write.csv(bb, “dirtydata_final.csv”) getwd() # xuất địa chỉ file được lưu

bar chart race ———————————————————-

p_ani <- bb %>% drop_na(delivery_charges) %>% count(nearest_warehouse, date) %>% arrange (date, desc(n)) %>% group_by(date) %>% #mutate(Noc_2 = tolower(countrycode(nearest_warehouse, “iso3c”, “iso2c”))) %>% drop_na() %>% mutate(rank = rank(order(n, decreasing = T))) %>% arrange(date, rank) %>% filter(date %in% 1:12) %>% ggplot(aes(x = rank, y = n)) + geom_col(fill = “azure3”, color = “black”, width = 0.7) + geom_text(aes(y = 0, label = date, size = 5)) + geom_text(aes(x = rank, y = 0, label = nearest_warehouse), size = 3) + coord_flip(expand = F, clip = “off”) + scale_x_reverse(limits = c(10.5 , 0)) + labs(x = ““, title =”“, y =”delivery_charges”) + theme( panel.background = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.title.x = element_text(margin = margin(t = 20), face = “bold”) ) + transition_states(date, transition_length = 4, state_length = 1) animate(p_ani, fps = 30, duration = 20, width = 700, height = 470, res = 120)

biểu đồ boxplot ——————————————————————–

i = file.choose() os = read.csv(i) # order_price ggplot(data = os, aes(x = order_price, y = delivery_charges, fill = gr_price))+ geom_boxplot() + geom_jitter(alpha = 0.5) + theme_bw() + labs(x = “order_price”, y = “delivery_charges”) + theme(axis.title.x = element_text(size = 10, margin = margin(t = 10)), axis.title.y = element_text(size = 10, margin = margin(r = 10)), plot.title = element_text(margin = margin(b = 10), face = “bold”, hjust = 0.5, size = 12) ) + theme(legend.position = “none”) os\(gr_price[os\)order_price < 10000] = “A” os\(gr_price[os\)order_price >= 10000 & os\(order_price < 20000] = "B" os\)gr_price[os$order_price >= 20000] = “C”

customer_lat

ggplot(data = os, aes(x = customer_lat, y = delivery_charges))+ geom_boxplot() + geom_jitter(alpha = 0.5) + theme_bw() + labs(x = “customer_lat”, y = “delivery_charges”) + theme(axis.title.x = element_text(size = 10, margin = margin(t = 10)), axis.title.y = element_text(size = 10, margin = margin(r = 10))) )

customer_long

ggplot(data = os, aes(x = customer_long, y = delivery_charges))+ geom_boxplot() + geom_jitter(alpha = 0.5) + theme_bw() + labs(x = “customer_long”, y = “delivery_charges”) + theme(axis.title.x = element_text(size = 10, margin = margin(t = 10)), axis.title.y = element_text(size = 10, margin = margin(r = 10))) )

order_total

os\(gr_total[os\)order_total < 10000] = “A” os\(gr_total[os\)order_total >= 10000 & os\(order_total < 20000] = "B" os\)gr_total[os$order_total >= 20000] = “C”

ggplot(data = os, aes(x = order_total, y = delivery_charges, fill = gr_total))+ geom_boxplot() + geom_jitter(alpha = 0.5) + theme_bw() + labs(x = “order_total”, y = “delivery_charges”) + theme(axis.title.x = element_text(size = 10, margin = margin(t = 10)), axis.title.y = element_text(size = 10, margin = margin(r = 10)), plot.title = element_text(margin = margin(b = 10), face = “bold”, hjust = 0.5, size = 12) ) + theme(legend.position = “none”)

distance_to_nearest_warehouse

os\(gr_dis[os\)distance_to_nearest_warehouse < 1] = “A” os\(gr_dis[os\)distance_to_nearest_warehouse >= 1 & os\(distance_to_nearest_warehouse < 2] = "B" os\)gr_dis[os$distance_to_nearest_warehouse >= 2] = “C”

ggplot(data = os, aes(x = distance_to_nearest_warehouse, y = delivery_charges, fill = gr_dis))+ geom_boxplot() + geom_jitter(alpha = 0.5) + theme_bw() + labs(x = “distance_to_nearest_warehouse”, y = “delivery_charges”) + theme(axis.title.x = element_text(size = 10, margin = margin(t = 10)), axis.title.y = element_text(size = 10, margin = margin(r = 10)), plot.title = element_text(margin = margin(b = 10), face = “bold”, hjust = 0.5, size = 12) ) + theme(legend.position = “none”)

corrplot —————————————————————-

library(corrplot) view(os) corrplot(os, method = “color”, type = “upper”, order = “hclust”, addrect = 2)