본문 바로가기

■ 프로그래밍/R

[R] Correlation Analysis 상관분석

[ R : Correlation Analysis 상관분석 ]


# 주석

## 결과값


패키지 설치 및 로딩하기

install.packages("corrplot")
install.packages("car")
install.packages("rgl")
install.packages("ggplot2")
install.packages("psych")
install.packages("writexl")
library(corrplot)
library(car)
library(rgl)
library(ggplot2)
library(psych)
library(writexl)


Correlation Analysis 상관분석

  • 언제 사용 하는가?
    A. 두 개의 양적 자료 간의 관련성(직선의 관계 = 선형의 관계)이 있는지를 통계적으로 분석하는 방법이다.

  • 자료: 양적자료 2개
    동일한 대상으로부터 다른 2개의 양적자료
    원인과 결과의 관계(인과관계)는 아니다. 인과관계는 회귀분석에서 다룬다.


1. 산점도(Scatter Plot)

예제 데이터: cars (R에 내장된 데이터)
변수명: speed(속도), dist(제동거리 = 브레이크를 밟았을 때 얼마나 밀리는지)


plot(data$variable = x축, data$variable = y축, col = 색, pch = 모양) 

http://kim-mj.tistory.com/41?category=810330의 barplot과 같이 main, ylab, ylim등과 같은 함수도 사용가능하다.


plot(cars$speed, cars$dist, col = "red", pch = 20)


ggplot2 패키지를 이용한 산점도

ggplot2::ggplot(data = mtcars,
                mapping = aes(x = wt, y = mpg)) + 
  geom_point()

기본 모양의 ggplot 산점도.
그 다음에는 계속 +로 추가한다.

아래 코드는 하나씩 추가하면서 변화를 직접 눈으로 확인하는 것을 추천한다.

ggplot2::ggplot(data = mtcars,
                mapping = aes(x = wt, y = mpg)) + 
  geom_point(aes(col = "red")) +                   # 점 색깔
  theme_classic() +                                # 배경
  labs(title = "Scatter Plot of wt & mpg",
       x = "Weight of Car",
       y = "Mile Per Gallon") +                    # 제목, 축 이름
  theme(plot.title = element_text(size = 20), 
        axis.title.x = element_text(size = 10),
        axis.title.y = element_text(size = 10)) +  # 제목 글씨 수정
  facet_wrap(~cyl)                                 # cyl의 factor별로 표시


ggplot2::ggplot(data = mtcars,
                mapping = aes(x = wt, y = mpg, col = cyl, fill = cyl)) + 
  geom_point()


col, fill을 cyl별로 나누어, 집단(4, 6, 8)마다 색이 달라짐.

ggplot2::ggplot(data = mtcars,
                mapping = aes(x = wt, y = mpg, col = cyl, size = cyl)) + 
  geom_point()


점의 모양이 바뀜.


2. 산점행렬도(SPM : Scatter Plot Matrix)

예제 데이터 : attitude(7개 모두 양적), iris(양적, 질적이 섞여있음)

plot(attitude)

plot(iris[ , 1:4])


corrplot::corrplot()

mtcars$cyl <- as.numeric(mtcars$cyl)
M <- cor(mtcars)
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(M, 
         method = "color", 
         col = col(200),
         type = "upper",
         order = "hclust", 
         number.cex = .7,
         addCoef.col = "black", 
         tl.col = "black", 
         tl.srt = 90, 
         sig.level = 0.01, 
         insig = "blank", 
         diag = FALSE)

corrplot Package 참고: https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html


3D Scatter Plot

예제데이터 : car, rgl packages

scatter3d(x = iris$Sepal.Length, 
          y = iris$Sepal.Width, 
          z = iris$Petal.Length, 
          groups = iris$Species,
          surface=FALSE, 
          grid = FALSE, 
          ellipsoid = TRUE)
## Loading required namespace: mgcv

참고: http://www.sthda.com/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization

(왜인지 Rmarkdown으로 나타나지지 않는다.. 결과는 url 참고)



3. 상관계수(Coefficient of Correation)

Pearson의 상관계수
- r: -1 ~ 1
- r의 절대값이 1에 가까워 질수록 관련성이 높아짐/강해짐
- r의 절대값이 0에 가까워 질수록 관련성이 없음
- r의 부호가 양수이면 양의 상관관계, 음수이면 음의 상관관계

상관계수의 해석에 대한 일반적인 가이드
  • r의 절대값 : 0.0 이상 ~ 0.2 미만 : 관련성이 없다
  • r의 절대값 : 0.2 이상 ~ 0.4 미만 : 약한 관련성이 있다
  • r의 절대값 : 0.4 이상 ~ 0.6 미만 : 보통의 관련성이 있다
  • r의 절대값 : 0.6 이상 ~ 0.8 미만 : 높은 관련성이 있다
  • r의 절대값 : 0.8 이상 ~ 1.0 이하 : 매우 높은 관련성이 있다
  • 도메인마다 기준은 다름


cor(data$variable, data$variable, method = "pearson")
method = kendall, spearman


cor(cars$speed, cars$dist, method = "pearson") ## 0.867

양의 상관계수에 가까움.

cor(attitude, method = "pearson")
##               rating complaints privileges  learning    raises  critical
## rating     1.0000000  0.8254176  0.4261169 0.6236782 0.5901390 0.1564392
## complaints 0.8254176  1.0000000  0.5582882 0.5967358 0.6691975 0.1877143
## privileges 0.4261169  0.5582882  1.0000000 0.4933310 0.4454779 0.1472331
## learning   0.6236782  0.5967358  0.4933310 1.0000000 0.6403144 0.1159652
## raises     0.5901390  0.6691975  0.4454779 0.6403144 1.0000000 0.3768830
## critical   0.1564392  0.1877143  0.1472331 0.1159652 0.3768830 1.0000000
## advance    0.1550863  0.2245796  0.3432934 0.5316198 0.5741862 0.2833432
##              advance
## rating     0.1550863
## complaints 0.2245796
## privileges 0.3432934
## learning   0.5316198
## raises     0.5741862
## critical   0.2833432
## advance    1.0000000


전부다 양적 자료이기 때문에 행렬로 나타내줌

cor(iris[ , 1:4], method = "pearson")
##              Sepal.Length Sepal.Width Petal.Length Petal.Width
## Sepal.Length    1.0000000  -0.1175698    0.8717538   0.8179411
## Sepal.Width    -0.1175698   1.0000000   -0.4284401  -0.3661259
## Petal.Length    0.8717538  -0.4284401    1.0000000   0.9628654
## Petal.Width     0.8179411  -0.3661259    0.9628654   1.0000000



4. 상관분석

  • 귀무가설: 두 양적 자료 간의 관련성(직선의 관계 = 선형의 관계)이 없다
  • 대립가설: 두 양적 자료 간의 관련성이 있다


[예제1] : cars(speed, dist)
- 귀무가설: speed와 dist간에는 관련성이 없다
- 대립가설: speed와 dist간에는 관련성이 있다


1단계. 정규성 검정
  • 귀무가설: 정규분포를 따른다
  • 대립가설: 정규분포를 따르지 않는다
shapiro.test(cars$speed) ## p값 = 0.45
shapiro.test(cars$dist)  ##p값 = 0.04

결론: 정규분포를 따르지 않는다


2단계. Kendall, Spearman이 만든 비모수 방법
cor.test(data$vairable, data$variable, method = "kendall" or "spearman")

정규성 가정이 깨졌거나 자료가 순서형(순위형) 자료로 되어 있을 때 사용
- Spearson은 양적 자료에만
- 검정력은 pearson이 더 뛰어남

cor.test(cars$speed, cars$dist, method = "kendall")  ## tau라는 상관계수 0.669
cor.test(cars$speed, cars$dist, method = "spearman") ## rho라는 상관계수 0.830

결론: 유의확률이 0.000이므로, 유의수준 0.05에서 speed와 dist 간에는 통계적으로 유의한 양의 상관관계가 있는 것으로 나타났다.


2단계. 만약 정규성 가정이 만족 되었다면
cor.test(data$vairable, data$variable, method = "pearson")


cor.test(cars$speed, cars$dist, method = "pearson")
## 
##  Pearson's product-moment correlation
## 
## data:  cars$speed and cars$dist
## t = 9.464, df = 48, p-value = 1.49e-12
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.6816422 0.8862036
## sample estimates:
##       cor 
## 0.8068949

결론: 유의확률이 0.000이므로, 유의수준 0.05에서 speed와 dist 간에는 통계적으로 유의한 양의 상관관계가 있는 것으로 나타났다(t = 9.464, p < 0.001).


[예제2 : attitude]

psych::corr.test(data, method = "pearson", "kendall", "spearman") : 상관계수, 유의확률을 계산해줌

한번 따라해보자.

psych::corr.test(attitude, method = "pearson")
attitude.corr.test <- psych::corr.test(attitude, method = "pearson")
str(attitude.corr.test) # list로 저장
attitude.corr.test$r # 추출해보는 연습
round(attitude.corr.test$r, digits = 3)
round(attitude.corr.test$p, digits = 3)
result <- rbind(round(attitude.corr.test$r, digits = 3), 
                round(attitude.corr.test$p, digits = 3))
result


[실습1 : iris]

psych::corr.test(iris[ , 1:4], method = "pearson")

위의 코드를 토대로 따라해보자.


'■ 프로그래밍 > R' 카테고리의 다른 글

[R] Linear Regression Analysis 선형회귀분석  (2) 2018.09.04
[R] ANOVA (Analysis of Variance)  (0) 2018.08.25
[R] Paired Test  (0) 2018.08.25
[R] Two Sample T-test  (0) 2018.08.25
[R] One Sample Test (단일 표본 검정)  (0) 2018.08.25