# 필요한 패키지 불러오기
library(dplyr)
## 
## 다음의 패키지를 부착합니다: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# 인터넷에서 CSV 파일 읽기
url <- "https://raw.githubusercontent.com/rich-hyun/kufa_data_1/main/14year_kufa_data.csv"
kufa_data <- read.csv(url, header = TRUE, sep = ",", stringsAsFactors = FALSE)

# kufa_data에서 w14pbb03에서 NA 값 제거
data_no_na <- dplyr::filter(kufa_data, !is.na(w14pbb03))

# 데이터에서 w14pbb03, h14inc, h14exp 변수 선택
selected_data <- dplyr::select(data_no_na, w14pbb03, h14inc, h14exp) %>%
  head(5)

print(selected_data)
##   w14pbb03 h14inc   h14exp
## 1    11010   6847 7593.816
## 2    11140   5730       NA
## 3    99999    540 2207.000
## 4    11080   5240       NA
## 5    11030   4902 4004.483
# w14pbb03를 기준으로 각 도시별 h14inc 평균과 거주 인구 수 계산
city_income_avg <- data_no_na %>%
  group_by(w14pbb03) %>%
  summarise(
    Average_Income = mean(h14inc, na.rm = TRUE), # 평균 소득 계산
    Residents_Count = n() # 해당 도시의 거주자 수
  )

# 결과 출력
print(city_income_avg)
## # A tibble: 239 × 3
##    w14pbb03 Average_Income Residents_Count
##       <int>          <dbl>           <int>
##  1    11010          6333.              22
##  2    11020          7832               19
##  3    11030         10118.              24
##  4    11040         10549.              38
##  5    11050          7188.              26
##  6    11060          7130.              37
##  7    11070          8420.              24
##  8    11080          7835.              43
##  9    11090          6625.              28
## 10    11100          7222.              20
## # ℹ 229 more rows
# h14inc와 h14exp의 상관계수를 계산합니다.
correlation <- cor(data_no_na$h14inc, data_no_na$h14exp, use = "complete.obs")

# 상관계수를 출력합니다.
print(correlation)
## [1] 0.6048364
library(ggplot2)

# 산점도를 그리기 위해 ggplot2 사용
ggplot(data_no_na, aes(x = h14inc, y = h14exp)) +
  geom_point() +
  theme_minimal() +
  ggtitle("h14inc와 h14exp의 관계") +
  xlab("소득 (h14inc)") +
  ylab("지출 (h14exp)")
## Warning: Removed 1228 rows containing missing values (`geom_point()`).

# ggplot으로 산점도를 그리고 가로축(x-axis) 범위를 0부터 1e+05까지로 설정합니다.
ggplot(data_no_na, aes(x = h14inc, y = h14exp)) +
  geom_point() +
  theme_minimal() +
  ggtitle("h14inc와 h14exp의 관계") +
  xlab("소득 (h14inc)") +
  ylab("지출 (h14exp)") +
  scale_x_continuous(limits = c(0, 1e+05)) # x축 범위 설정
## Warning: Removed 1228 rows containing missing values (`geom_point()`).

# ggplot으로 산점도를 그리고 가로축(x-axis) 범위를 0부터 75,000까지로 설정합니다.
ggplot(data_no_na, aes(x = h14inc, y = h14exp)) +
  geom_point() +
  theme_minimal() +
  ggtitle("h14inc와 h14exp의 관계") +
  xlab("소득 (h14inc)") +
  ylab("지출 (h14exp)") +
  scale_x_continuous(limits = c(0, 75000)) # x축 범위 설정
## Warning: Removed 1228 rows containing missing values (`geom_point()`).

# 단순회귀분석 모델을 만듭니다.
model <- lm(h14exp ~ h14inc, data = data_no_na)

# 회귀분석 결과를 요약하여 출력합니다.
summary(model)
## 
## Call:
## lm(formula = h14exp ~ h14inc, data = data_no_na)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -19341  -1318   -353    881  48307 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2.316e+03  9.758e+01   23.73   <2e-16 ***
## h14inc      4.516e-01  1.179e-02   38.31   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2544 on 2544 degrees of freedom
##   (결측으로 인하여 1228개의 관측치가 삭제되었습니다.)
## Multiple R-squared:  0.3658, Adjusted R-squared:  0.3656 
## F-statistic:  1468 on 1 and 2544 DF,  p-value: < 2.2e-16
#p-value가 2e-16으로 매우 작기에 통계적으로 유희
#R스퀘어 36.58
#ad-R스퀘어 36.56 R스퀘어와 비슷하므로 불필요한 변수추가되지 않음
#F통계량 1468, p밸류값과 같이 보면 통계적으로 유의
#잔차 -19341~48307
#잔차 중앙값 -353
#잔차 표준오차 2544


# 이상치를 식별하는 함수를 정의합니다.
find_outliers <- function(data, column) {
  # 결측값을 제외하고 사분위수를 계산합니다.
  Q1 <- quantile(data[[column]], 0.25, na.rm = TRUE)
  Q3 <- quantile(data[[column]], 0.75, na.rm = TRUE)
  IQR <- Q3 - Q1
  lower_bound <- Q1 - 1.5 * IQR
  upper_bound <- Q3 + 1.5 * IQR
  
  # 이상치를 TRUE, 정상치를 FALSE로 표시하는 논리 벡터를 반환합니다.
  return(data[[column]] < lower_bound | data[[column]] > upper_bound)
}

# h14inc와 h14exp에 대해 이상치를 찾습니다.
data_no_na$outlier_inc <- find_outliers(data_no_na, "h14inc")
data_no_na$outlier_exp <- find_outliers(data_no_na, "h14exp")

# 이상치인지 여부를 나타내는 하나의 컬럼을 생성합니다.
data_no_na$outlier <- data_no_na$outlier_inc | data_no_na$outlier_exp

# 이상치를 빨간색으로, 정상 데이터를 검은색으로 산점도에 표시합니다.
# x축 범위를 0부터 1e+05 (100,000)까지 설정합니다.
ggplot(data_no_na, aes(x = h14inc, y = h14exp, color = outlier)) +
  geom_point() +
  scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) +
  theme_minimal() +
  ggtitle("h14inc와 h14exp의 관계") +
  xlab("소득 (h14inc)") +
  ylab("지출 (h14exp)") +
  xlim(c(0, 75000)) # x축 범위 설정
## Warning: Removed 1228 rows containing missing values (`geom_point()`).

# 이상치 식별
data_no_na$outlier_inc <- find_outliers(data_no_na, "h14inc")
data_no_na$outlier_exp <- find_outliers(data_no_na, "h14exp")
data_no_na$outlier <- data_no_na$outlier_inc | data_no_na$outlier_exp

# 이상치가 아닌 데이터만 필터링
clean_data <- data_no_na %>% filter(!outlier)

# 이상치를 제외한 데이터를 사용하여 선형 모델 생성
model_clean <- lm(h14exp ~ h14inc, data = clean_data)

# 모델 요약 결과 출력
summary(model_clean)
## 
## Call:
## lm(formula = h14exp ~ h14inc, data = clean_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4452.7 -1152.3  -219.1   918.6  8153.3 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2.045e+03  7.640e+01   26.77   <2e-16 ***
## h14inc      4.702e-01  1.048e-02   44.87   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1652 on 2420 degrees of freedom
## Multiple R-squared:  0.4541, Adjusted R-squared:  0.4539 
## F-statistic:  2013 on 1 and 2420 DF,  p-value: < 2.2e-16
# 이상치를 제외한 데이터로 산점도를 그립니다.
ggplot(clean_data, aes(x = h14inc, y = h14exp)) +
  geom_point() +
  theme_minimal() +
  ggtitle("Cleaned Data: h14inc와 h14exp의 관계") +
  xlab("소득 (h14inc)") +
  ylab("지출 (h14exp)") +
  scale_x_continuous(limits = c(0, 75000)) # x축 범위 설정

#기본 모델의 잔차 범위는 -19341에서 48307까지
#->이상치 제거 모델의 잔차 범위는 -4452.7에서 8153.3까지
#계수는 약 0.4516-> 0.4702
#이상치를 제거한 후, h14inc의 계수가 증가, 이는 소득이 지출에 더 큰 영향
#결정계수 0.3658->0.4541
#F-통계량: 1468->2013, p-value동일, 변수의 영향 증가
#잔차 표준 오차 2544->1652