2. 상관분석

2.1상관계수

  • 상관 분석은 두 변수 사이의 관련성을 파악하는 방법이다.
  • 대표적으로는 피어슨 상관 계수로 상관 분석을 한다.
  • 피어슨 상관 계수는 한 변수가 커질 때 다른 변수가 함께 커지는 공분산을 표준편차로 나눈 값을 사용한다.
cor(iris$Sepal.Width, iris$Sepal.Length)
## [1] -0.1175698
cor(iris$Petal.Length, iris$Sepal.Width)
## [1] -0.4284401

2.1.1 피어슨 상관 계수

  • 두 확률 변수 사이의 선형적 상관 관계 측정
  • -1 ~ 1 사이의 값을 갖는다.
x1 <- c(1, 3, 5, 8, 10)
x2 <- c(-2, 3, 8, 5, 9)
cor(x1, x2)
## [1] 0.8238904

2.1.2 상관 계수의 시각화

  • symnum(x) 를 사용
x <- iris[, 1:4]
head(x)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4
cor(x)
##              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
symnum(cor(x))    # symnum -1 ~ 1 사이의 숫자를 심볼로 표현한다.
##              S.L S.W P.L P.W
## Sepal.Length 1              
## Sepal.Width      1          
## Petal.Length +   .   1      
## Petal.Width  +   .   B   1  
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
                  # 복잡한 상관관계를 간단하게 표현 가능

2.1.3 스피어만 상관 계수

  • 실제값 대신 두 값의 순위를 사용해 상관계수를 구하는 방식
  • 비선형 상관 관계도 측정 가능
  • 국어 점수와 영어 점수의 상관관계는 피어슨 상관계수로, 석차의 상관관계는 스피어만 상관계수로 구한다.
kor <- c(85, 90, 87, 92, 95)    # rank(kor) : 1, 3,.2, 4, 5
eng <- c(88, 89, 68, 84, 91)    # rank(eng) : 3, 4, 1, 2, 5
m <- matrix(c(kor, eng), ncol = 2) 
cor(m, method = "spearman")
##      [,1] [,2]
## [1,]  1.0  0.5
## [2,]  0.5  1.0

2.1.4 패키지를 이용한 시각화

  • 다양한 패키지들이 있지만, corrgram(x)를 사용
#install.packages("corrgram")
library(corrgram)
corrgram(x)

corrgram(iris, upper.panel = panel.conf)

2.2 상관계수 검정

  • 상관계수의 통계적 유의성을 살펴본다
  • 귀무가설은 ‘상관계수가 0이다’
cor.test(x1, x2)
## 
##  Pearson's product-moment correlation
## 
## data:  x1 and x2
## t = 2.5179, df = 3, p-value = 0.08634
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.2137461  0.9879934
## sample estimates:
##       cor 
## 0.8238904
cor.test(x1, x2, method = "spearman")
## 
##  Spearman's rank correlation rho
## 
## data:  x1 and x2
## S = 2, p-value = 0.08333
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
## rho 
## 0.9

연습문제

  1. 피어슨 상관계수를 통해 다음을 검증하시오.
  • Pclass와 Fare의 피어슨 상관계수의 값은 얼마인가?
  • 그 값이 음수를 갖는다면 그 의미는 무엇인가?
Data <- read.csv("train.csv")
cor(Data$Fare, as.numeric(Data$Pclass))
## [1] -0.5494996
corrgram(Data, upper.panel = panel.conf)

# Pclass의 등급이 좋을 수록(=낮을 수록), 운임이 높다 라는 것을 의미한다. 반비례 관계인 것이다.
  1. 타이타닉 데이터 중 Survived, Pclass, Fare, Sex를 추출하여 상관 관계를 구하시오.
for_corr <- data.frame(Data$Pclass, Data$Fare)
colnames(for_corr) <- c("Pclass", "Fare")
for_corr$Pclass <- as.integer(for_corr$Pclass)
for_corr$Sex <- as.integer(Data$Sex)
for_corr$Survived <- as.integer(Data$Survived)
str(for_corr)  # 자료의 형태 확인
## 'data.frame':    891 obs. of  4 variables:
##  $ Pclass  : int  3 1 3 1 3 3 1 3 3 2 ...
##  $ Fare    : num  7.25 71.28 7.92 53.1 8.05 ...
##  $ Sex     : int  2 1 1 1 2 2 2 2 1 1 ...
##  $ Survived: int  0 1 1 1 0 0 0 0 1 1 ...
cor(for_corr)  # 상관계수 출ㄹ
##              Pclass       Fare        Sex   Survived
## Pclass    1.0000000 -0.5494996  0.1319005 -0.3384810
## Fare     -0.5494996  1.0000000 -0.1823328  0.2573065
## Sex       0.1319005 -0.1823328  1.0000000 -0.5433514
## Survived -0.3384810  0.2573065 -0.5433514  1.0000000
  1. 이전에 구한 상관 계수를 다음 과정을 따라 시각화 하고, 결과를 해석하시오 -survived와 가장 연관성이 높은 변수는 무엇인가?
library(corrgram)
corrgram(for_corr, upper.panel = panel.conf)

운임과는의 0.24로 양의 상관계수를 갖는다. 따라서 생존율과 운임은 연관이 있다고 보여진다.

2.3 집단 차이 분석

  • 추론 통계는 표본을 통해 모집단의 특성을 추정한다.
  • 추론 통계 함수를 이용하여 모집단과 표본 또는 두 집단 사이의 차이를 분석하는 방법을 살펴본다

2.3.1 일표본 평균

  • 하나의 모집단으로 부터 표본을 추출하여 평균 신뢰구간 구하기
alternative = c("two.sided", "less", "greater")  # 대립가설(다르다, 작다, 크ㄷ)
mu = 0                                           # 평균

x <- rnorm(30) 
t.test(x)
## 
##  One Sample t-test
## 
## data:  x
## t = 0.89999, df = 29, p-value = 0.3755
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  -0.2101083  0.5403378
## sample estimates:
## mean of x 
## 0.1651148

2.3.2 독립 이표본 평균

  • 두 모집단에서 독립적인 표본을 추출하여 두 모집단의 평균이 같은지 살펴봄
  • 다음과 같은 절차를 따른다.
  1. 데이터 확인
head(sleep)
##   extra group ID
## 1   0.7     1  1
## 2  -1.6     1  2
## 3  -0.2     1  3
## 4  -1.2     1  4
## 5  -0.1     1  5
## 6   3.4     1  6
tail(sleep)
##    extra group ID
## 15  -0.1     2  5
## 16   4.4     2  6
## 17   5.5     2  7
## 18   1.6     2  8
## 19   4.6     2  9
## 20   3.4     2 10
sleep2 <- sleep[, c(1,2)]
head(sleep2)
##   extra group
## 1   0.7     1
## 2  -1.6     1
## 3  -0.2     1
## 4  -1.2     1
## 5  -0.1     1
## 6   3.4     1
  1. 모분산이 같은지 확인
  • 분산의 비가 같다는 귀무가설
var.test(extra ~ group, sleep2)
## 
##  F test to compare two variances
## 
## data:  extra by group
## F = 0.79834, num df = 9, denom df = 9, p-value = 0.7427
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
##  0.198297 3.214123
## sample estimates:
## ratio of variances 
##          0.7983426
  1. t.test()
  • 모평균에 차이가 없다는 귀무가설
t.test(extra ~ group, data = sleep2, paired = FALSE, var.equal = TRUE)
## 
##  Two Sample t-test
## 
## data:  extra by group
## t = -1.8608, df = 18, p-value = 0.07919
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -3.363874  0.203874
## sample estimates:
## mean in group 1 mean in group 2 
##            0.75            2.33

2.3.3 짝지은 이표본 평균

  • 두 모집단에서 연관된 표본을 추출하여 두 모집단의 평균이 같은지를 살펴봄
  • 데이터 확인 후 바로 test()를 사용
t.test(sleep$extra[sleep$group == 1], sleep$extra[sleep$group == 2], paired = TRUE)
## 
##  Paired t-test
## 
## data:  sleep$extra[sleep$group == 1] and sleep$extra[sleep$group == 2]
## t = -4.0621, df = 9, p-value = 0.002833
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -2.4598858 -0.7001142
## sample estimates:
## mean of the differences 
##                   -1.58

2.3.4 일표본 비율1

  • 표본으로 부터 모집단의 비율을 추정 및 가설 검정할 때 사용한다.
  • 찬성과 반대 중 어느 쪽의 비율이 큰 지를 추정할 때 사용할 수 있다.
  • 정규분포 근사를 사용한다.
# 100 명 중 42명이 찬성했다면 찬성 비율이 50%라고 할 수 있을까?
#prop.test(42, 100)
prop.test(42, 100, 0.5)
## 
##  1-sample proportions test with continuity correction
## 
## data:  42 out of 100, null probability 0.5
## X-squared = 2.25, df = 1, p-value = 0.1336
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.3233236 0.5228954
## sample estimates:
##    p 
## 0.42

2.3.5 일표본 비율2

  • 표본으로 부터 모집단의 비율을 추정 및 가설 검정할 때 사용된다.
  • 찬성과 반대 중 어느 쪽의 비율이 큰 지를 추정할 때 사용할 수 있다.
  • 정규분포 근사를 사용하지 않고, 신뢰구간을 직접 계산한다.
# 100 명 중 42명이 찬성했다면 찬성 비율이 50%라고 할 수 있을까?
#binom.test(42, 100)
binom.test(42, 100, 0.5)
## 
##  Exact binomial test
## 
## data:  42 and 100
## number of successes = 42, number of trials = 100, p-value = 0.1332
## alternative hypothesis: true probability of success is not equal to 0.5
## 95 percent confidence interval:
##  0.3219855 0.5228808
## sample estimates:
## probability of success 
##                   0.42

2.3.6 이표본 비율

  • 두 표본으로부터 모집단의 비율을 추정 및 가설 검정할 때 사용한다.
  • 예로, 남성의 흡연율과 여성의 흡연율에 차이가 있는지를 비교할 때 사용할 수 있다.
# 남성 100명 중 45명, 여성 90명 중 55명이 흡연한다면 두 비율에 차이가 있을까?
prop.test(c(45, 55), c(100, 90))
## 
##  2-sample test for equality of proportions with continuity
##  correction
## 
## data:  c(45, 55) out of c(100, 90)
## X-squared = 4.3067, df = 1, p-value = 0.03796
## alternative hypothesis: two.sided
## 95 percent confidence interval:
##  -0.31185005 -0.01037217
## sample estimates:
##    prop 1    prop 2 
## 0.4500000 0.6111111