# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R
#     language: R
#     name: ir
# ---

library(ggfortify)  # autoplot
library(dplyr)      # select
library(ggplot2)    # ggplot
library(gridExtra)  # grid
library(olsrr)      # hadi

# Data Load
setwd('D:/Working/03.Korea/회귀분석/Final-Report/google-play-store-apps')
gplay_data <- read.csv(file="googleplaystore.csv", header=TRUE, sep=",")

gplay_data <- subset(gplay_data, Category == "GAME")     # Category 항목을 GAME 데이터만 사용 
gplay_data <- subset(gplay_data, Type == "Paid")         # Type 항목을 Paid 데이터만 사용
gplay_data <- subset(gplay_data, Last_Updated == "2017") # 업데이트 2017 년도의 데이터만 사용
rownames(gplay_data) <- 1:nrow(gplay_data)               # index 초기화.
gplay_data <- gplay_data %>% dplyr::select(-Category, -Type, -Last_Updated)  # 결정 된 항목의 열을 삭제

# 전체 적합
gplay_reg = lm(Rating ~ ., gplay_data)
summary(gplay_reg)

# +
p1 <- ols_plot_resid_stand(gplay_reg)$plot     # Standardized Residuals Chart
p2 <- ols_plot_cooksd_chart(gplay_reg)$plot    # Cook's D Chart
p3 <- ols_plot_dffits(gplay_reg)$plot          # DFFITS
p4 <- ols_plot_hadi(gplay_reg)                 # H

grid.arrange(p1, p2, p3, p4, ncol=2, nrow=2)
# -

par(mfrow=c(2,2))
plot(gplay_reg)

gplay_data <- gplay_data[c(-13,-14,-19),]    # 13, 14, 19 데이터 제거

gplay_reg = lm(Rating ~ ., gplay_data)
summary(gplay_reg)

par(mfrow=c(2,2))
plot(gplay_reg)

panel.cor <- function(x,y,digits=2, prefix="", cex.cor,...)
{
  usr <- par("usr"); on.exit(par(usr))
  par(usr=c(0,1,0,1))
  r <- abs(cor(x,y))
  txt <- format(c(r,0.123456789),digits=digits)[1]
  txt <- paste0(prefix,txt)
  if(missing(cex.cor))
      cex.cor <- 1.5/strwidth(txt)
  text(0.5,0.5,txt, cex=cex.cor*r)
}

# panel.cor 함수는 pairs 함수 사용할때 상관계수 크기에 따라 텍스트크기가 변하도록 해주는 사용자 정의 함수 
pairs(gplay_data ,
    lower.panel=function(x,y){ 
        points(x,y);
        abline(lm(y ~ x), col='red')
    },
    upper.panel = panel.cor
)

library(usdm)
vif(gplay_data)

gplay_paid_cor <- cor(gplay_data)
gplay_eigen <- eigen(gplay_paid_cor)$val
c_index_gplay <- sqrt(gplay_eigen[1]/gplay_eigen)
c_index_gplay

step(gplay_reg, direction="both")

gplay_data <- gplay_data %>% dplyr::select(-Installs)
vif(gplay_data)
gplay_paid_cor <- cor(gplay_data)
gplay_eigen <- eigen(gplay_paid_cor)$val
c_index_gplay <- sqrt(gplay_eigen[1]/gplay_eigen)
c_index_gplay

gplay_reg = lm(Rating ~ ., gplay_data)
summary(gplay_reg)

par(mfrow=c(2,2))
plot(gplay_reg)

autoplot(gplay_reg
         , colour = "black"
         , label.colour ="red"
         , smooth.colour = "blue"
         , ad.colour = "red")

StarcoderdataJupyterScriptsDedupFiltered