rm(list = ls())
# 잔차분석(residual analysis)은 회귀모형의 타당성을 진단하기 위한
# 핵심 절차입니다. 잔차를 분석함으로써 회귀모형의 기본
# 가정(선형성, 정규성, 등분산성, 독립성)이 만족되는지를 확인할 수 있습니다.
model <- lm(mpg~hp, data = mtcars) # 독립변수 1개, 단순선형(직선) 회귀
summary(model)
##
## Call:
## lm(formula = mpg ~ hp, data = mtcars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.7121 -2.1122 -0.8854 1.5819 8.2360
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 30.09886 1.63392 18.421 < 2e-16 ***
## hp -0.06823 0.01012 -6.742 1.79e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.863 on 30 degrees of freedom
## Multiple R-squared: 0.6024, Adjusted R-squared: 0.5892
## F-statistic: 45.46 on 1 and 30 DF, p-value: 1.788e-07
par(mfrow = c(2,2))
plot(model, which = 1)
# 회귀모형을 적합한 후 plot(model) 명령어로 확인할 수 있는 잔차 플롯
# 4가지는 회귀모형의 가정이 잘 만족되는지 진단하는 중요한 도구입니다.
# 각 which = 1~4 플롯의 의미와 해석은 다음과 같습니다
# Residuals vs Fitted Plot (잔차 대 적합값 플롯)
# 목적: 선형성(linearity) 및 등분산성(homoscedasticity) 검정-> 시험!
# 이상적 모습: 잔차들이 0을 중심으로 무작위로 흩어짐
# U자형 / 곡선 → 비선형 관계 존재 가능성
# 잔차의 퍼짐이 점점 커짐/작아짐 → 이분산성 존재 가능성
# 이분산성이란, 회귀분석에서 잔차의 분산이 일정하지
# 않은 현상을 의미합니다.
# mtcars는 선형성과 등분산성을 위배한 것이다. 유형 : 무엇을 위배했는지?
# install.packages("lmtest")
library(lmtest)
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
dwtest(model)
##
## Durbin-Watson test
##
## data: model
## DW = 1.1338, p-value = 0.00411
## alternative hypothesis: true autocorrelation is greater than 0
# Durbin-Watson Test for Autocorrelation (자기상관 검정)
# p-value < 0.05 → 잔차 간에 자기상관 있음 → 독립성 가정 위반
# DW 통계량은 보통 2에 가까우면 이상적 (1보다 작으면 양의 자기상관 의심)
plot(model, which = 2)
# Normal Q-Q Plot (정규 Q-Q 플롯)
# 이상적 모습: 점들이 대각선 위에 일직선
# 꼬리가 위나 아래로 휘어짐 → 잔차가 정규분포가 아닐 수 있음
# 극단값 존재 → 이상치 영향 의심
plot(model, which = 3)
# Scale-Location Plot (√|Standardized Residuals| vs Fitted)
# 목적: 등분산성(Homoscedasticity) 검정
# 이상적 모습: 점들이 고르게 흩어짐 (수평선 주변에 무작위 분포)
# 위쪽으로 퍼지거나 깔때기 모양 → 이분산성 존재
plot(model, which = 4)

# Cook’s Distance Plot
# 목적: 영향력 있는 관측치 식별
# 이상적 모습: 모든 관측치가 낮은 쿡의 거리 값
# 특정 관측치가 다른 점들보다 월등히 높은 경우 → 해당 점이 모델에 큰 영향
data("faithful")
model1 <- lm(eruptions~waiting, data = faithful)
summary(model1)
##
## Call:
## lm(formula = eruptions ~ waiting, data = faithful)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.29917 -0.37689 0.03508 0.34909 1.19329
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.874016 0.160143 -11.70 <2e-16 ***
## waiting 0.075628 0.002219 34.09 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4965 on 270 degrees of freedom
## Multiple R-squared: 0.8115, Adjusted R-squared: 0.8108
## F-statistic: 1162 on 1 and 270 DF, p-value: < 2.2e-16
dwtest(model1)
##
## Durbin-Watson test
##
## data: model1
## DW = 2.561, p-value = 1
## alternative hypothesis: true autocorrelation is greater than 0
# Durbin-Watson Test for Autocorrelation (자기상관 검정)
# p-value > 0.05 → 잔차 간에 자기상관 없음
# DW 통계량은 보통 2이상이기 때문에 이상적임
par(mfrow = c(2,2))
plot(model1, which = 1)
# Residuals vs. Fitted Plot
# 빨간선이 휘어짐을 보이기 때문에 선형성 위배 X -> 좀 더 확인해봐야함
# 잔차들이 비슷한 폭으로 퍼져있지 않기 때문에 등분산성 위배 O
plot(model1, which = 2)
# Normal Q-Q Plot (정규 Q-Q 플롯)
# 이상적 모습: 점들이 대각선 위에 일직선
# 꼬리가 위나 아래로 휘어짐 → 잔차가 정규분포가 아닐 수 있음 X
# 애매하게 꼬리가 휘어져 있어서 애매해 O
plot(model1, which = 3)
# Scale-Location Plot (√|Standardized Residuals| vs Fitted)
# 목적: 등분산성(Homoscedasticity) 검정
# 이상적 모습: 점들이 고르게 흩어짐 (수평선 주변에 무작위 분포)
# 패턴이 보임 → 이분산성 존재
plot(model1, which = 4)

# Cook’s Distance Plot
# 목적: 영향력 있는 관측치 식별
# 이상적 모습: 모든 관측치가 낮은 쿡의 거리 값
# 특정 관측치(158, 197, 203)가 다른 점들보다 월등히 높은 경우
# → 해당 점이 모델에 큰 영향
data(pressure)
model2 <- lm(pressure~temperature, data = pressure)
summary(model2)
##
## Call:
## lm(formula = pressure ~ temperature, data = pressure)
##
## Residuals:
## Min 1Q Median 3Q Max
## -158.08 -117.06 -32.84 72.30 409.43
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -147.8989 66.5529 -2.222 0.040124 *
## temperature 1.5124 0.3158 4.788 0.000171 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 150.8 on 17 degrees of freedom
## Multiple R-squared: 0.5742, Adjusted R-squared: 0.5492
## F-statistic: 22.93 on 1 and 17 DF, p-value: 0.000171
dwtest(model2)
##
## Durbin-Watson test
##
## data: model2
## DW = 0.24119, p-value = 6.249e-10
## alternative hypothesis: true autocorrelation is greater than 0
# Durbin-Watson Test for Autocorrelation (자기상관 검정)
# p-value < 0.05 → 잔차 간에 자기상관 있음 → 독립성 가정 위반
# DW 통계량은 보통 2에 가까우면 이상적 (1보다 작으면 양의 자기상관 의심)
par(mfrow = c(2,2))
plot(model2, which = 1)
# Residuals vs. Fitted Plot
# 빨간선이 U자형을 보이기 때문에 선형성 위배
# 오른쪽에서 잔차들이 비슷한 폭으로 퍼져있지 않기 때문에 등분산성 위배
plot(model2, which = 2)
# Normal Q-Q Plot (정규 Q-Q 플롯)
# 이상적 모습: 점들이 대각선 위에 일직선
# 꼬리가 위나 아래로 휘어짐 → 잔차가 정규분포가 아닐 수 있음
# 극단값 존재 → 이상치 영향 의심
plot(model2, which = 3)
# Scale-Location Plot (√|Standardized Residuals| vs Fitted)
# 목적: 등분산성(Homoscedasticity) 검정
# 이상적 모습: 점들이 고르게 흩어짐 (수평선 주변에 무작위 분포)
# 수평선 주변에 없고 패턴을 보이기 때문에 → 이분산성 존재
plot(model2, which = 4)

# Cook’s Distance Plot
# 목적: 영향력 있는 관측치 식별
# 이상적 모습: 모든 관측치가 낮은 쿡의 거리 값
# 특정 관측치(1, 18, 19)가 다른 점들보다 월등히 높은 경우
# → 해당 점이 모델에 큰 영향
data(women)
model3 <- lm(weight~height, data = women)
summary(model3)
##
## Call:
## lm(formula = weight ~ height, data = women)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.7333 -1.1333 -0.3833 0.7417 3.1167
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -87.51667 5.93694 -14.74 1.71e-09 ***
## height 3.45000 0.09114 37.85 1.09e-14 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.525 on 13 degrees of freedom
## Multiple R-squared: 0.991, Adjusted R-squared: 0.9903
## F-statistic: 1433 on 1 and 13 DF, p-value: 1.091e-14
dwtest(model3)
##
## Durbin-Watson test
##
## data: model3
## DW = 0.31538, p-value = 1.089e-07
## alternative hypothesis: true autocorrelation is greater than 0
# Durbin-Watson Test for Autocorrelation (자기상관 검정)
# p-value < 0.05 → 잔차 간에 자기상관 있음 → 독립성 가정 위반
# DW 통계량은 보통 2에 가까우면 이상적 (1보다 작으면 양의 자기상관 의심)
par(mfrow = c(2,2))
plot(model3, which = 1)
# Residuals vs. Fitted Plot
# 빨간선이 U자형을 보이기 때문에 선형성 위배
# 잔차들의 분포는 좋음 등분산성 위배안함
plot(model3, which = 2)
# Normal Q-Q Plot (정규 Q-Q 플롯)
# 이상적 모습: 점들이 대각선 위에 일직선
# 꼬리가 위나 아래로 휘어짐 → 잔차가 정규분포가 아닐 수 있음
# 극단값 존재 → 이상치 영향 의심
plot(model3, which = 3)
# Scale-Location Plot (√|Standardized Residuals| vs Fitted)
# 목적: 등분산성(Homoscedasticity) 검정
# 이상적 모습: 점들이 고르게 흩어짐 (수평선 주변에 무작위 분포)
# 수평선 주변에 없기 때문에 → 이분산성 존재
plot(model3, which = 4)

# Cook’s Distance Plot
# 목적: 영향력 있는 관측치 식별
# 이상적 모습: 모든 관측치가 낮은 쿡의 거리 값
# 특정 관측치(1, 14, 15)가 다른 점들보다 월등히 높은 경우
# → 해당 점이 모델에 큰 영향
# 성별과 바느질 점수 데이터 생성
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
gender <- factor(c(rep("male", 10), rep("female", 10)))
score <- c(70, 72, 68, 75, 74, 71, 73, 76, 69, 72,
65, 66, 64, 67, 63, 62, 68, 66, 65, 64)
# 회귀분석은 독립, 종속 모두 구간척도 이상이어야 합니다.
# 독립변수가 범주형일 때(=더미변수)도 회귀분석은 가능하다.
df <- data.frame(gender, score)
glimpse((df))
## Rows: 20
## Columns: 2
## $ gender <fct> male, male, male, male, male, male, male, male, male, male, fem…
## $ score <dbl> 70, 72, 68, 75, 74, 71, 73, 76, 69, 72, 65, 66, 64, 67, 63, 62,…
model <- lm(score ~ gender, data = df)
summary(model)
##
## Call:
## lm(formula = score ~ gender, data = df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.00 -1.25 0.00 1.25 4.00
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 65.0000 0.7071 91.92 < 2e-16 ***
## gendermale 7.0000 1.0000 7.00 1.55e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.236 on 18 degrees of freedom
## Multiple R-squared: 0.7313, Adjusted R-squared: 0.7164
## F-statistic: 49 on 1 and 18 DF, p-value: 1.554e-06
# install.packages("car") # 한 번만 설치
library(car) # 매번로드
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
##
## recode
data(mtcars)
model <- lm(mpg~wt + hp + disp, data = mtcars)
vif(model)
## wt hp disp
## 4.844618 2.736633 7.324517