단순 회귀모형 실습

단순 회귀분석 예제

1
2
data(cars)
head(cars)
1
2
3
4
5
6
7
##   speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10

독립변수는 speed이고, 종속 변수는 dist라고 본다.

식은 dist(Y)=X0+X1*(speed)+e

이 데이터를 회귀분석한다.

1
2
m1<-lm(dist~speed,cars)
summary(m1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## 
## Call:
## lm(formula = dist ~ speed, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -29.069 -9.525 -2.272 9.215 43.201
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -17.5791 6.7584 -2.601 0.0123 *
## speed 3.9324 0.4155 9.464 1.49e-12 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 15.38 on 48 degrees of freedom
## Multiple R-squared: 0.6511, Adjusted R-squared: 0.6438
## F-statistic: 89.57 on 1 and 48 DF, p-value: 1.49e-12

여기서 Intercept는 y절편을 의미한다. x0 = -17.579

speed는 회귀선의 기울기를 의미한다. x1 = 3.932

그래서 식은 dist(Y)=-17.579 + (3.932)*(speed)+e 로 구해질 수 있다.
유의수준 5%하에서 F-통계량의 p-값이 0.05보다 작기때문에 추정된 회귀식은 통계적으로
유의하다고 볼 수 있다.

이렇게 추정한 회귀모형을 그래프로 소개하고자 한다.

1
2
3
4
library(ggplot2)
ggplot(m1,aes(x=speed,y=dist))+
geom_point(shape=1)+#중앙이 빈 동그라미 만들기 shape=1
stat_smooth(method='lm',se=F) #단순선형회귀분석옵션method='lm',se=F 표준오차를 표현하지않는다는 것.
1
## `geom_smooth()` using formula 'y ~ x'

이 회귀선이 타당한지 보기위해 회귀식과 모형간의 잔차를 따로 구할 수 있다.

그리고, 이 잔차가 정규 분포를 따르는지 확인한다.

1
2
res_m1<-residuals(m1)
shapiro.test(res_m1)
1
2
3
4
5
## 
## Shapiro-Wilk normality test
##
## data: res_m1
## W = 0.94509, p-value = 0.02152

귀무가설: 정규분포를 따르지 않는다.

대립가설: 정규분포를 따른다.

여기서 p-value가 0.02152 기 때문에, 귀무가설을 기각할 수 있고 따라서 이 회귀선의 잔차는 정규분포를 따른다.

이 모형은 회귀가정들을 만족할까?

1
2
par(mfrow=c(2,2))
plot(m1)

왼쪽 위의 그림을 보면 그래프의 기울기가 거의 0에 가까우므로 선형성 가정을 만족한다.

오른쪽 위의 그림을 보면 23,35,40 을 제외한 값들은 *잔차 정규성(정상성)*이 확인된다.

왼쪽 아래의 그림을 보면 그래프의 기울기가 거의 0에 가까우므로 등분산성 가정을 만족한다.

오른쪽 밑의 그림에서는 23번과 49번의 이상치가 확인된다.

독립성 가정을 만족하는지 확인하기 위해 durbinWatson 검정을 시행한다.

1
2
#install.packages("durbinWatsonTest")
library(car)
1
## Loading required package: carData
1
durbinWatsonTest(m1)
1
2
3
##  lag Autocorrelation D-W Statistic p-value
## 1 0.1604322 1.676225 0.214
## Alternative hypothesis: rho != 0

귀무가설: 잔차들 사이에 자기상관관계가 없다.
대립가설: 잔차가 자기상관관계가 있다.

여기서 p-value가 매우 크므로, 귀무가설을 채택하여 잔차들 사이에 상관관계가 없다는 뜻이다. 그러므로 독립성을 만족한다.

모든 가설을 만족하므로 이 회귀분석은 타당하다고 할 수 있다.

빅데이터 시각화 시험

통계학 강의

귀무 가설 : 어떠한 가설이 관련성이 없다고 가정한다.
대립 가설 : 어떠한 가설이 관련성이 있다고 가정한다.
X-squared: 어떠한 기준점을 갖고 통계량을 구해서 대립/귀무 가설중에 고르는 지표
p-value (유의 확률) : 귀무 가설이 맞다는 전제하에 표본에서 실제로 관측된 통계치와 같거나 더 극단적인 통계치가 관측될 확률. 특정값(0.05,0.01등)보다 작을 경우 귀무가설을 기각한다.(대립 가설 채택) 하지만 높게 나오면 귀무가설을 채택한다.

  1. 척도별 기술 통계량 구하기
1
2
3
data <- read.csv("2_day/data/descriptive.csv", stringsAsFactors = FALSE)

head(data) # 데이터의 상위 6개
1
2
3
4
5
6
7
##   resident gender age level cost type survey pass
## 1 1 1 50 1 5.1 1 1 2
## 2 2 1 54 2 4.2 1 2 2
## 3 NA 1 62 2 4.7 1 1 1
## 4 4 2 50 NA 3.5 1 4 1
## 5 5 1 51 1 5.0 1 3 1
## 6 3 1 55 2 5.4 1 3 NA
1
dim(data) # 차원 보기
1
## [1] 300   8
1
length(data) # 변수의 길이 (열 11개)
1
## [1] 8
1
length(data$survey) # survey 칼럼의 관측치 (행 32개)
1
## [1] 300
1
summary(data) #수치형의 기술통계형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
##     resident         gender          age            level      
## Min. :1.000 Min. :0.00 Min. :40.00 Min. :1.000
## 1st Qu.:1.000 1st Qu.:1.00 1st Qu.:48.00 1st Qu.:1.000
## Median :2.000 Median :1.00 Median :53.00 Median :2.000
## Mean :2.233 Mean :1.42 Mean :53.88 Mean :1.836
## 3rd Qu.:3.000 3rd Qu.:2.00 3rd Qu.:60.00 3rd Qu.:2.000
## Max. :5.000 Max. :5.00 Max. :69.00 Max. :3.000
## NA's :21 NA's :13
## cost type survey pass
## Min. :-457.200 Min. :1.00 Min. :1.00 Min. :1.000
## 1st Qu.: 4.425 1st Qu.:1.00 1st Qu.:2.00 1st Qu.:1.000
## Median : 5.400 Median :1.00 Median :3.00 Median :1.000
## Mean : 8.752 Mean :1.27 Mean :2.61 Mean :1.432

## 3rd Qu.: 6.300 3rd Qu.:2.00 3rd Qu.:3.00 3rd Qu.:2.000
## Max. : 675.000 Max. :2.00 Max. :5.00 Max. :2.000
## NA's :30 NA's :26 NA's :113 NA's :20
1
2
3
4
5
# 위 소스를 실행하고 나면, 각 갈럼 최대, 최소, 평균, 중간 값을 확인할 수 있다. 
# NA's는 각 데이터의 Missing Values를 의미한다.

## gender를 확인해보자.
summary(data$gender)
1
2
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## 0.00 1.00 1.00 1.42 2.00 5.00
1
table(data$gender) # 각 값의 빈도수를 알 수 있도록 도와주는 함수임
1
2
3
## 
## 0 1 2 5
## 2 173 124 1
1
2
3
4
5
#gender에서 1이 몇개인지, 2가 몇개인지 출력해줌.

# 이상치 제거 소스 코드 예제~~~~
data <- subset(data, data$gender == 1 | data$gender == 2) #0일때와 2일때를 제외한다.
table(data$gender)
1
2
3
## 
## 1 2
## 173 124

2. 기술 통계량 분석 보고서 작성

기술 통계량은 말 그대로 빈도수와 percent(%)로 구성.
패키지 활용으로 통계량 쉽게 구하기
PrettyR 패키지에서 freq() 함수 사용

#EX 1. 거주지역

1
2
3
4
#install.packages("prettyR")
library(prettyR)

freq(data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
## 
## Frequencies for resident
## 1 2 5 3 4 NA
## 131 54 44 30 17 21
## % 44.1 18.2 14.8 10.1 5.7 7.1
## %!NA 47.5 19.6 15.9 10.9 6.2
##
##
## Frequencies for gender
## 1 2 NA
## 173 124 0
## % 58.2 41.8 0
## %!NA 58.2 41.8
##
##
## Frequencies for age
## 48 49 47 65 55 45 63 51 54 46 58 60 64 56 57 50 61 59 52 62 53 69 40 42 44 68 NA
## 32 30 24 24 23 19 18 13 13 12 11 10 10 9 9 8 8 6 4 4 3 3 1 1 1 1 0
## % 10.8 10.1 8.1 8.1 7.7 6.4 6.1 4.4 4.4 4 3.7 3.4 3.4 3 3 2.7 2.7 2 1.3 1.3 1 1 0.3 0.3 0.3 0.3 0
## %!NA 10.8 10.1 8.1 8.1 7.7 6.4 6.1 4.4 4.4 4 3.7 3.4 3.4 3 3 2.7 2.7 2 1.3 1.3 1 1 0.3 0.3 0.3 0.3
##
##
## Frequencies for level
## 1 2 3 NA
## 115 99 70 13
## % 38.7 33.3 23.6 4.4
## %!NA 40.5 34.9 24.6
##
##
## Frequencies for cost
## 5 6.3 4 6 6.2 6.4 5.1 4.1 5.2 5.5 6.1 6.7 5.3 3 4.7 5.7 3.5 4.3 4.6 5.4 5.8 4.4 4.9 5.6 6.5 6.8 6.9 7.7 3.8 3.9 4.2 7 7.1 -235.8 -5.9 2.3 3.3 3.4 4.8 5.9 7.2 7.9 75.1 85.1 115.7 336.5 -457.2 -345.6 -75 -4.8 2.1 4.5 225.8 257.8 675 NA
## 18 16 15 14 13 11 10 9 9 8 8 8 7 6 6 6 5 5 5 5 5 4 4 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 30
## % 6.1 5.4 5.1 4.7 4.4 3.7 3.4 3 3 2.7 2.7 2.7 2.4 2 2 2 1.7 1.7 1.7 1.7 1.7 1.3 1.3 1.3 1.3 1.3 1.3 1.3 1 1 1 1 1 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 10.1
## %!NA 6.7 6 5.6 5.2 4.9 4.1 3.7 3.4 3.4 3 3 3 2.6 2.2 2.2 2.2 1.9 1.9 1.9 1.9 1.9 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.1 1.1 1.1 1.1 1.1 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.4 0.4 0.4 0.4 0.4 0.4 0.4 0.4 0.4
##
##
## Frequencies for type
## 1 2 NA
## 197 74 26
## % 66.3 24.9 8.8
## %!NA 72.7 27.3
##
##
## Frequencies for survey
## 2 3 4 1 5 NA
## 72 61 25 20 7 112
## % 24.2 20.5 8.4 6.7 2.4 37.7
## %!NA 38.9 33 13.5 10.8 3.8
##
##
## Frequencies for pass
## 1 2 NA
## 158 119 20
## % 53.2 40.1 6.7
## %!NA 57 43
1
2
3
4
5
6
7
# (1) 변수의 리코딩 using base R
data$resident2[data$resident == 1] <- "특별시"
data$resident2[data$resident >= 2 & data$resident <= 4 ] <- "광역시"
data$resident2[data$resident == 5] <- "시구군"
#resident 의 숫자가 1이면 특별시, 2~4면 광역시 5면 시구군으로 구분해서 resident2에 넣음.

prop.table(table(data$resident2)) #resident2의 전체에서 차지하는 비율을 보기위한 함수. 특별한 값을 주지않으면 전체합이 1로 맞춰져서 나온다.
1
2
3
## 
## 광역시 시구군 특별시
## 0.3659420 0.1594203 0.4746377
1
2
# (2) 변수의 리코딩 dplyr 버전
library(dplyr)
1
2
## 
## Attaching package: 'dplyr'
1
2
3
## The following objects are masked from 'package:stats':
##
## filter, lag
1
2
3
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
1
2
3
4
5
6
7
8
data$resident3 <- recode(data$resident, 
`1` ='거제도',
`2` = '광역시',
`3` = '광역시',
`4` = '광역시',
`5` = '시구군'
)
prop.table(table(data$resident3))
1
2
3
## 
## 거제도 광역시 시구군
## 0.4746377 0.3659420 0.1594203

#EX 2. 성별

1
2
3
4
data$gender2[data$gender == 1] <- "남자" #gender가 1 인것을 남자로 gender2에 넣음
data$gender2[data$gender == 2] <- "여자"

round(prop.table(table(data$gender2)),2) #gender2 의 전체에서 차지하는 비율을 보기위한 함수. 전체합이 2로 맞춰져서 나온다.
1
2
3
## 
## 남자 여자
## 0.58 0.42

#EX 3. 나이

1
2
3
4
5
data$age2[data$age <= 45] <- "중년층"
data$age2[data$age >= 46 & data$age <= 59] <- "장년층"
data$age2[data$age >= 60] <- "노년층"

round(prop.table(table(data$age2)), 2)
1
2
3
## 
## 노년층 장년층 중년층
## 0.26 0.66 0.07
1
2
3
4
5
6
#### (4) 학력 ####
data$level2[data$level == 1] <- "고졸"
data$level2[data$level == 2] <- "대졸"
data$level2[data$level == 3] <- "대학원졸"

round(prop.table(table(data$level2)), 2)
1
2
3
## 
## 고졸 대졸 대학원졸
## 0.40 0.35 0.25
1
2
3
#### (5) 합격 ####
data$pass2[data$pass == 1] <- "합격"
data$pass2[data$pass == 2] <- "불합격"

3. 교차 분석

교차분석은 범주형 자료를 대상으로 두개 이상의 변수들에 대한 관련성을 알아보기 위한 것이며, 교차 분할표를 작성하고 이를 통해서 변수 상호 간의 관련성 여부를 분석하는 방법임.

교차분석시 일반적인 고려사항

-교차분석에 사용되는 변수는 값이 10미만인 범주형 변수(명목척도, 서열척도)이어야 하며, 비율척도인 경우 코딩변경을 통해서 범주형 자료로 변환해야 함.
-학년의 경우 초등학교는 1, 중학교는 2, 고등학교는 3 대학교는 4 등으로 범주화 하여 변경을 한다.

1
2
3
4
5
6
#### (1) 패키지 설치 ####

library(gmodels)

#### (2) 교차 분할표 생성) ####
CrossTable(x = data$level2, y = data$pass2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
## 
##
## Cell Contents
## |-------------------------|
## | N |
## | Chi-square contribution |
## | N / Row Total |
## | N / Col Total |
## | N / Table Total |
## |-------------------------|
##
##
## Total Observations in Table: 266
##
##
## | data$pass2
## data$level2 | 불합격 | 합격 | Row Total |
## -------------|-----------|-----------|-----------|
## 고졸 | 48 | 59 | 107 |
## | 0.143 | 0.105 | |
## | 0.449 | 0.551 | 0.402 |
## | 0.425 | 0.386 | |
## | 0.180 | 0.222 | |
## -------------|-----------|-----------|-----------|
## 대졸 | 34 | 58 | 92 |
## | 0.661 | 0.488 | |
## | 0.370 | 0.630 | 0.346 |
## | 0.301 | 0.379 | |
## | 0.128 | 0.218 | |
## -------------|-----------|-----------|-----------|
## 대학원졸 | 31 | 36 | 67 |
## | 0.226 | 0.167 | |
## | 0.463 | 0.537 | 0.252 |
## | 0.274 | 0.235 | |
## | 0.117 | 0.135 | |
## -------------|-----------|-----------|-----------|
## Column Total | 113 | 153 | 266 |
## | 0.425 | 0.575 | |
## -------------|-----------|-----------|-----------|
##
##
1
2
3
# 이거 원래 실행되는데....knit 하니까 안됨.

(107 * 153) / 266
1
## [1] 61.54511
1
((59-61.54) ^ 2) / 61.54
1
## [1] 0.1048359

4. 카이 제곱 검정 (chi-square Test)

카이제곱검정(Chi-Square Test)은 범주(Category)별로 관측빈도와 기대빈도의 차이를 통해서 확률 모형이 데이터를 얼마나 잘 설명하는지를 검정하는 통계적 방법임

카이제곱검정 중요사항

  • 카이제곱검정을 위해서는 교차분석과 동일하게 범주형 변수를 대상으로 함
  • 집단별로 비율이 같은지를 검정하여 독립성 여부를 검정함
  • 유의확률에 의해서 집단 간의 ‘차이가 있는가?’ 또는 ‘차이가 없는가?’로 가설 검증함
  • CrossTable() 함수에 ‘chisq = TRUE’ 속성을 적용하면 카이제곱 검정 결과를 볼 수 있다.

(1). 독립성 검정

  • 동일 집단의 두 변인을 대상으로 관령성이 있는가? 또는 없는가? 를 검정하는 방법임.
    독립성 검정 가설의 예)
    귀무가설: 경제력과 대학진학 합격률과 관련성이 없다(=독립적이다)
    대립가설: 경제력과 대학진학 합격률과 관련성이 있다(=독립적이지 않다)
1
2
3
# 귀무가설: 부모의 학력 수준과 자녀의 대학진학 여부는 관련성이 없다. 
# 대립가설(=연구가설): 부모의 학력 수준과 자녀의 대학진학 여부는 관련성이 있다.
CrossTable(x = data$level2, y = data$pass2, chisq = TRUE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
## 
##
## Cell Contents
## |-------------------------|
## | N |
## | Chi-square contribution |
## | N / Row Total |
## | N / Col Total |
## | N / Table Total |
## |-------------------------|
##
##
## Total Observations in Table: 266
##
##
## | data$pass2
## data$level2 | 불합격 | 합격 | Row Total |
## -------------|-----------|-----------|-----------|
## 고졸 | 48 | 59 | 107 |
## | 0.143 | 0.105 | |
## | 0.449 | 0.551 | 0.402 |
## | 0.425 | 0.386 | |
## | 0.180 | 0.222 | |
## -------------|-----------|-----------|-----------|
## 대졸 | 34 | 58 | 92 |
## | 0.661 | 0.488 | |
## | 0.370 | 0.630 | 0.346 |
## | 0.301 | 0.379 | |
## | 0.128 | 0.218 | |
## -------------|-----------|-----------|-----------|
## 대학원졸 | 31 | 36 | 67 |
## | 0.226 | 0.167 | |
## | 0.463 | 0.537 | 0.252 |
## | 0.274 | 0.235 | |
## | 0.117 | 0.135 | |
## -------------|-----------|-----------|-----------|
## Column Total | 113 | 153 | 266 |
## | 0.425 | 0.575 | |
## -------------|-----------|-----------|-----------|
##
##
## Statistics for All Table Factors
##
##
## Pearson's Chi-squared test
## ------------------------------------------------------------
## Chi^2 = 1.790291 d.f. = 2 p = 0.4085481
##
##
##
1
2
# 기대빈도 구하기
(113 * 107) / 266 # 고졸 불합격
1
## [1] 45.45489
1
(153 * 107) / 266 # 고졸 합격
1
## [1] 61.54511
1
(113 * 92) / 266 # 대졸 불합격
1
## [1] 39.08271
1
(153 * 92) / 266 # 대졸 합격
1
## [1] 52.91729
1
(113 * 67) / 266 # 대학원졸 불합격
1
## [1] 28.46241
1
(153 * 67) / 266 # 대학원졸 합격
1
## [1] 38.53759

논문이나 보고서에서는 귀무가설을 기각하고, 연구가설을 채택하는 것이 목적임.

#유의확률 해석 방법
-유의확률(P-value: 0.408)
-유의확률(p-value: 0.4085)이 0.05 이상이기 때문에 유의미한 수준(a = 0.05)에서 귀무가설을 기각할 수 없다.
-따라서, 귀무가설을 기각할 수가 없고, 부모의 학력 수준과 자녀의 대학진학 여부와는 관련성이 없는 것으로 분석됨.

5. 집단간 차이 분석

1
2
3
4
5
6
7
8
N <- 20000 # 표본 크기(N) > 신뢰수준 95%의 신뢰구간 구하기
X <- 170.1 # 표본 평균(X)
S <- 2 # 표본 표준편차(S)

low <- X - 1.96 * S/sqrt(N) # 신뢰구간 하한값
high <- X + 1.96 * S/sqrt(N) # 신뢰구간 하한값

low; high
1
## [1] 170.0723
1
## [1] 170.1277
1
2
3
# 신뢰수준 95%의 모평균 신뢰구간: 170.0723 <= m <= 170.1277
# 표본오차 구하기
(low - X) * 100 # -2.771
1
## [1] -2.771859
1
(high - X) * 100 # 2.771
1
## [1] 2.771859
1
# 표본오차는 +- 2.77

(1) 단일집단 비율 검정

데이터셋
CS교육 데이터
연구환경 예시
2018년도 CS 시, 고객의 불만율 20%였음
이를 개선하기 위해, 2019년도 CS 150명 고객 대상 설문결과 20명만 불만을 가지고 있음
Q: 기존 20%보다 불만율이 낮아졌을까?
귀무가설: 기존 2018년도 고객 불만율과 2019년도 CS교육 후, 불만율에 차이가 없다.
연구가설: 기존 2019년도 고객 불만율과 2019년도 CS교육 후, 불만율에 차이가 있다.

1
2
3
library(prettyR)

getwd()
1
## [1] "C:/Users/1/Desktop/R_edu/R_NCS_2020"
1
2
cs_data <- read.csv("2_day/data/one_sample.csv", stringsAsFactors = FALSE)
head(cs_data)
1
2
3
4
5
6
7
##   no gender survey time
## 1 1 2 1 5.1
## 2 2 2 0 5.2
## 3 3 2 1 4.7
## 4 4 2 1 4.8
## 5 5 2 1 5.0
## 6 6 2 1 5.4
1
table(cs_data$survey) # 0: 불만족(14), 1: 만족(136)
1
2
3
## 
## 0 1
## 14 136
1
freq(cs_data$survey)
1
2
3
4
5
6
## 
## Frequencies for cs_data$survey
## 1 0 NA
## 136 14 0
## % 90.7 9.3 0
## %!NA 90.7 9.3
1
2
3
4
# 이항분포 비율 검정
# 명목척도의 비율을 바탕으로 binom.test() 함수를 이용하여 이항분포의 양측 검정을 통해, 검정 통계량을 구한 후 이를 이용하여 가설 검정
# binom.test()
binom.test(c(136, 14), p = 0.8)
1
2
3
4
5
6
7
8
9
10
11
## 
## Exact binomial test
##
## data: c(136, 14)
## number of successes = 136, number of trials = 150, p-value = 0.0006735
## alternative hypothesis: true probability of success is not equal to 0.8
## 95 percent confidence interval:
## 0.8483615 0.9480298
## sample estimates:
## probability of success
## 0.9066667
1
2
# 방향성이 없는 양측 검정
binom.test(c(136, 14), p = 0.8) #p는 확률
1
2
3
4
5
6
7
8
9
10
11
## 
## Exact binomial test
##
## data: c(136, 14)
## number of successes = 136, number of trials = 150, p-value = 0.0006735
## alternative hypothesis: true probability of success is not equal to 0.8
## 95 percent confidence interval:
## 0.8483615 0.9480298
## sample estimates:
## probability of success
## 0.9066667
1
2
3
4
5
# 만족고객 136명을 대상으로 95% 신뢰 수준에서 양측 검정을 실시한 결과 검정 통계량(p-value)값은 0.00006735로 유의수준 0.05보다 작기 때문에 기존 만족률(80%)과 차이가 있다고 볼 수 있음.
# 다만, 여기서 주의해야 할 점은, 우리가 원하는 답! 2018년보다 만족도가 증가했는지, 감소했는지, 방향성은 알지 못한다. 방향성을 알기 원한다면 이 때에는 단측검정을 사용한다.

# 방향성이 있는 단측 검정
binom.test(c(136, 14), p = 0.8, alternative = "greater", conf.level = 0.95)
1
2
3
4
5
6
7
8
9
10
11
## 
## Exact binomial test
##
## data: c(136, 14)
## number of successes = 136, number of trials = 150, p-value = 0.0003179
## alternative hypothesis: true probability of success is greater than 0.8
## 95 percent confidence interval:
## 0.8579426 1.0000000
## sample estimates:
## probability of success
## 0.9066667

alternative = “greater”의 뚯은, 150명 중에서 136명의 만족 고객이 전체비율의 80%보다 더 큰 비율인가를 검정하기 위한 속성임.
p-value 값은 0.0003179로 유의수준 0.05보다 작기 때문에 기존 만족률보다 80% 이상의 효과를 얻을 수 있음.
결과적으로 기존 20%보다 불만율이 낮아졌다고 할 수 있음
따라서, 귀무가설이 기각되고, 연구가설이 채택됨 = CS교육에 효과가 있다고 볼 수 있음.

(2) 단일표본 T 검정 :그륩간에 비교하려고함. 정규분포를 따른다.

-데이터가 주어지면 T검정을 바로 시행히지는 않는다.

  • shapiro.test()를 통해서 정규분포를 따르는지 따르지 않는지에 따라 검정 방법이 달라집니다.

정규분포를 따른다면 t.test() / 정규분포를 따르지 않는다면 wilcox.test()를 시행합니다.

1
2
3
4
5
6
7
8
# 연구환경
# A 동영상 앱의 평균 사용시간이 5.2시간으로 발표가 된 상황에서 B 동영상의 평균 사용시간과 차이가 있는지를 검정하기 위해 B 업체 고객의 설문조사를 실시한 하였다. 150명의 설문조사를 실시한 데이터를 가지고 검정을 실시한다.

# 연구가설
# 귀무가설, A 동영상 앱과 B 동영상 앱의 평균 사용시간에 차이가 없다.
# 대립가설, A 동영상 앱과 B 동영상 앱의 평균 사용시간에 차이가 있다.
time_data <- read.csv("2_day/data/one_sample.csv", stringsAsFactors = FALSE)
str(time_data)
1
2
3
4
5
## 'data.frame':	150 obs. of  4 variables:
## $ no : int 1 2 3 4 5 6 7 8 9 10 ...
## $ gender: int 2 2 2 2 2 2 2 2 2 1 ...
## $ survey: int 1 0 1 1 1 1 1 1 0 1 ...
## $ time : num 5.1 5.2 4.7 4.8 5 5.4 NA 5 4.4 4.9 ...
1
summary(time_data$time) # NA 41개임 확인
1
2
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
## 3.000 5.000 5.500 5.557 6.200 7.900 41
1
2
# NA를 제외한 평균 (1)
mean(time_data$time, na.rm = TRUE)
1
## [1] 5.556881
1
2
3
# NA 제거 후 새로운 데이터 생성 (2)
time_data2 <- time_data[is.na(time_data$time) == FALSE, ] #결측치 제거
mean(time_data2$time)
1
## [1] 5.556881
1
2
3
4
# 정규분포 검정
# shapiro.test의 귀무가설: x의 데이터는 정규분포이다 / 대립가설: x의 데이터는 정규분포가 아니다. ************
# 즉, 유의확률(p > 0.05)보다 크면 x의 데이터는 정규분포이라는 뜻임
shapiro.test(time_data2$time) #*************** t.test를 하기전에 꼭 해야함
1
2
3
4
5
## 
## Shapiro-Wilk normality test
##
## data: time_data2$time
## W = 0.99137, p-value = 0.7242
1
2
3
# p-value = 0.7242, 유의확률보다 높기 때문에 모수검정인 T검정을 실시한다. 데이터가 정규분포가 아니면 비모수 검정
# 정규분포 시각화
hist(time_data2$time)

1
2
qqnorm(time_data2$time)
qqline(time_data2$time, lty = 1, col = "blue") #정규분포는 선주변에 값들이 몰려있다.

1
2
# t-test 양측 검정 & 단측 검정
t.test(time_data2$time, mu = 5.2) # 차이가 있다 없다 검정. 다른 집단의 평균은 5.2 기때문에 mu=5.2로 넣음
1
2
3
4
5
6
7
8
9
10
11
## 
## One Sample t-test
##
## data: time_data2$time
## t = 3.9461, df = 108, p-value = 0.0001417
## alternative hypothesis: true mean is not equal to 5.2
## 95 percent confidence interval:
## 5.377613 5.736148
## sample estimates:
## mean of x
## 5.556881
1
2
3
4
5
# 유의 수준이 0.05보다 작기 때문에 귀무가설을 기각하고 대립가설을 채택한다. 
# 대립가설: A 앱 평균 시청 시간과 B 앱 평균 시청 시간의 차이가 있다.
#mu=5.5로 하면 p-value가 크게 늘어난다. 이것은 mu와 표본평균이 거의비슷하다는 뜻이다.

t.test(time_data2$time, alter = "greater", mu = 5.2) # 5.2보다 크다 작다
1
2
3
4
5
6
7
8
9
10
11
## 
## One Sample t-test
##
## data: time_data2$time
## t = 3.9461, df = 108, p-value = 7.083e-05
## alternative hypothesis: true mean is greater than 5.2
## 95 percent confidence interval:
## 5.406833 Inf
## sample estimates:
## mean of x
## 5.556881
1
2
3
4
5
6
# 귀무가설: B앱의 평균 사용 시간이 A앱의 평균 사용시간보다 크지 않다.
#alter="greater"로 큰지 작은지 확인 alternative hypothesis: true mean is greater than 5.2 이 값이 5.2와 같지않다
#mu값에따라 p-value 값이 변하는 것을 보며 표본의 적합도를 판단하기.

# 'B앱의 평균 시청시간이 더 길다'라는 방향성을 갖는 연구가설 검정 결과 P-value값이 유의확률 이내임.
# 따라서, B회사의 앱 사용 시간이 A회사의 평균 5.2시간보다 더 긴 것을 확인할 수 있음.

(3) 두 집단 비율 검정

  • 독립표본 이항분포의 비율 검정은 prop.test() VS. 단일표본 이항분포 binom.test() 비교
  • 비율 차이 검정 통계량을 바탕으로 귀무가설의 기각 여부를 결정함.
1
2
data <- read.csv("2_day/data/two_sample.csv", header = TRUE)
summary(data)
1
2
3
4
5
6
7
8
##        no             gender         method        survey           score      
## Min. : 1.00 Min. :1.00 Min. :1.0 Min. :0.0000 Min. :3.000
## 1st Qu.: 75.75 1st Qu.:1.00 1st Qu.:1.0 1st Qu.:1.0000 1st Qu.:5.100
## Median :150.50 Median :1.00 Median :1.5 Median :1.0000 Median :5.600
## Mean :150.50 Mean :1.42 Mean :1.5 Mean :0.8167 Mean :5.685
## 3rd Qu.:225.25 3rd Qu.:2.00 3rd Qu.:2.0 3rd Qu.:1.0000 3rd Qu.:6.300
## Max. :300.00 Max. :2.00 Max. :2.0 Max. :1.0000 Max. :8.000
## NA's :73
1
2
3
# 데이터 전처리하기
# method 비율
table(data$method)
1
2
3
## 
## 1 2
## 150 150
1
2
3
4
# 1집단: 150명, 2: 150명

# survey 비율
table(data$survey)
1
2
3
## 
## 0 1
## 55 245
1
2
3
4
5
# 0 (불만족): 55명 / 1 (만족): 245명

# 두 변수에 대한 교차분석
# table(method, survey, useNA="ifany") # useNA="ifany": 결측치까지 출력
table(data$method, data$survey, useNA = "ifany")
1
2
3
4
##    
## 0 1
## 1 40 110
## 2 15 135
1
2
3
4
5
6
# 위 표 해석
# 300명 중 교육 방식에 만족했다고 응답한 사람은 245명임.
# 245명 중 교육방법 1에 만족한 사람은 110명 VS 교육방법 2에 만족한 사람은 135명

# 두 집단 비율 차이 검정*********************
prop.test(x = c(110, 135), n = c(150, 150))
1
2
3
4
5
6
7
8
9
10
11
## 
## 2-sample test for equality of proportions with continuity correction
##
## data: c(110, 135) out of c(150, 150)
## X-squared = 12.824, df = 1, p-value = 0.0003422
## alternative hypothesis: two.sided
## 95 percent confidence interval:
## -0.25884941 -0.07448392
## sample estimates:
## prop 1 prop 2
## 0.7333333 0.9000000
1
2
# 방향성을 갖는 단측가설 검정
prop.test(x = c(110, 135), n = c(150, 150), alter = "greater")
1
2
3
4
5
6
7
8
9
10
11
## 
## 2-sample test for equality of proportions with continuity correction
##
## data: c(110, 135) out of c(150, 150)
## X-squared = 12.824, df = 1, p-value = 0.9998
## alternative hypothesis: greater
## 95 percent confidence interval:
## -0.2451007 1.0000000
## sample estimates:
## prop 1 prop 2
## 0.7333333 0.9000000

첫번째 교육방법이 두번째 교육방법보다 만족율이 크지 않을것이라 가정하고 검정 진행
p-value 값이 0.9998이기 때문에 귀무가설을 채택함.
즉, 첫번째 교육방법이 두번째 교육방법보다 만족율이 크다로 분석할 수 있음.
p-value가 클수록 관계가 없다? 귀무가설이 맞다는 뜻.

(4) 두 집단 평균 검정(독립 표본 T 검정)

-평균 차이 검정을 위해서는 기술 통계량으로 평균을 구한다.
-독립표본 평균검정은 두 집단 간 분산의 동질성 검증(정규분포 검정) 여부를 판정한다.
-결과에 따라서, t.test를 진행하거나 윌콕스 검정을 수행한다.

1
summary(data)
1
2
3
4
5
6
7
8
##        no             gender         method        survey           score      
## Min. : 1.00 Min. :1.00 Min. :1.0 Min. :0.0000 Min. :3.000
## 1st Qu.: 75.75 1st Qu.:1.00 1st Qu.:1.0 1st Qu.:1.0000 1st Qu.:5.100
## Median :150.50 Median :1.00 Median :1.5 Median :1.0000 Median :5.600
## Mean :150.50 Mean :1.42 Mean :1.5 Mean :0.8167 Mean :5.685
## 3rd Qu.:225.25 3rd Qu.:2.00 3rd Qu.:2.0 3rd Qu.:1.0000 3rd Qu.:6.300
## Max. :300.00 Max. :2.00 Max. :2.0 Max. :1.0000 Max. :8.000
## NA's :73
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 여기에서 결측치 73개를 제외하는 코드를 작성한다. 
# base R 방식
result <- subset(data, !is.na(score), c(method, score))

# dplyr 방식
library(dplyr)

result2 <- data %>%
filter(!is.na(score)) %>%
select(method, score)

# 피벗 테이블 작성 & 기술 통계량
result %>%
group_by(method) %>%
summarise(length = n(),
avg_score = mean(score))
1
2
3
4
5
## # A tibble: 2 x 3
## method length avg_score
## <int> <int> <dbl>
## 1 1 109 5.56
## 2 2 118 5.80
1
2
3
4
5
6
7
8
9
10
# 동질성 검정
# 동질성 검정의 귀무가설: 두 집단 간 분포의 모양이 동질적이다.
# 동질성 검정의 대립가설: 두 집단 간 분포의 모양이 동질적이지 않다.
# var.test(x, y)에서 x와 y는 숫자형 벡터가 들어가야 한다. 분산 테스트?
# 동질성에 따라서 많이 다르면 비모수 검정을 한다.
# 따라서, 데이터셋에서 각 방법에 따라 숫자형 벡터로 변환하는 것이 중요하다.
method_1 <- subset(result, method == 1)
method_2 <- subset(result, method == 2)

var.test(method_1$score, method_2$score) #p-value에 의해 분산이 어느정도 동일하다고 판단되기때문에 t검증을 실행한다.
1
2
3
4
5
6
7
8
9
10
11
## 
## F test to compare two variances
##
## data: method_1$score and method_2$score
## F = 1.2158, num df = 108, denom df = 117, p-value = 0.3002
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
## 0.8394729 1.7656728
## sample estimates:
## ratio of variances
## 1.215768
1
2
3
# 검정 통계량 p-value 0.3002로 유의수준 0.05보다 크기 때문에 두 집단 간의 분포 형태가 동질하다고 볼 수 있음. 
# 즉, 이 때에는 윌콕스 검정이 아니라 t.test() 검정을 수행한다.
t.test(method_1$score, method_2$score)
1
2
3
4
5
6
7
8
9
10
11
## 
## Welch Two Sample t-test
##
## data: method_1$score and method_2$score
## t = -2.0547, df = 218.19, p-value = 0.0411
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -0.48296687 -0.01005133
## sample estimates:
## mean of x mean of y
## 5.556881 5.803390
1
2
3
4
5
6
# 차이가 있느냐 없느냐만 가늠함
# p-value = 0.0411이기 때문에, 두 집단 실기시험의 평균에는 차이가 있다로 결론내릴 수 있으나, 방법1이 좋은지 아니면 2가 좋은지는 판단하지 못함
# 이럴 때에는 방향성을 갖는 단측검정을 실시함

t.test(method_1$score, method_2$score,
alter="greater", conf.int = TRUE, conf.level = 0.95)
1
2
3
4
5
6
7
8
9
10
11
## 
## Welch Two Sample t-test
##
## data: method_1$score and method_2$score
## t = -2.0547, df = 218.19, p-value = 0.9794
## alternative hypothesis: true difference in means is greater than 0
## 95 percent confidence interval:
## -0.4446915 Inf
## sample estimates:
## mean of x mean of y
## 5.556881 5.803390
1
2
#귀무가설: method_2$score가 method_1$score 보다 크다
#대립가설: method_2$score가 method_1$score 크지 않다

p-value가 0.9794
귀무가설을 기각할 수 없기 때문에, method_2의 실기 시험 점수가 method_1의 점수보다 크다
따라서, 교육방법에 따른 두 집단 간 실기시험의 평균에 차이가 있고, method_2가 method_1보다 결과가 더 좋았다라고 결론 내릴 수 있음.

(5) 대응 두 집단 평균 검정 (대응 표본 T검정)

정책 효과, 마케팅 효과 등, 이런 것들을 검정할 때 매우 유용합니다.
참고로 마케팅 공부할 때, 가장 유용하고 사용했던 검정 방법이기도 합니다.
동일한 표본을 대상으로 측정된 두 변수의 평균 차이를 검정하는 분석방법임.

1
2
3
4
5
6
7
8
9
10
11
# 연구환경
# A교육센터에서 교육생 100명을 대상으로 교수법 프로그램 적용 전에 실기시험을 실시한 후 1개월 동안 동일한 교육생에세 교수법 프로그램을 적용한 후 실기시험을 실시한 점수와 평균에 차이가 있는지 검정합니다.

# 가설검정
# 귀무가설: 교수법 프로그램을 적용하기 전 학생들의 학습력과 교수법 프로그램을 적용한 후 학생들의 학습력에 차이가 없다.
# 연구가설: 교수법 프로그램을 적용하기 전 학생들의 학습력과 교수법 프로그램을 적용한 후 학생들의 학습력에 차이가 있다.

# 데이터 불러오기
#data <- read.csv("R_NCS_2020/2_day/data/paired_sample.csv", header = TRUE)
data <- read.csv("2_day/data/paired_sample.csv", header = TRUE)
summary(data)
1
2
3
4
5
6
7
8
##        no             before          after      
## Min. : 1.00 Min. :3.000 Min. :5.000
## 1st Qu.: 25.75 1st Qu.:4.800 1st Qu.:5.800
## Median : 50.50 Median :5.100 Median :6.200
## Mean : 50.50 Mean :5.145 Mean :6.221
## 3rd Qu.: 75.25 3rd Qu.:5.600 3rd Qu.:6.500
## Max. :100.00 Max. :7.000 Max. :8.000
## NA's :4
1
2
3
4
5
6
7
8
9
# 대응 두 집단 subset 생성하기
# dplyr way

result <- data %>%
filter(!(is.na(after))) %>%
select(before, after)

# 동질성 검정
var.test(result$before, result$after, paired = TRUE)
1
2
3
4
5
6
7
8
9
10
11
## 
## F test to compare two variances
##
## data: result$before and result$after
## F = 1.0718, num df = 95, denom df = 95, p-value = 0.7361
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
## 0.7151477 1.6062992
## sample estimates:
## ratio of variances
## 1.071793
1
2
3
4
5
# p-value 값이 0.05보다 크기 때문에 귀무가설을 그대로 채택함
# 귀무가설: 두 그룹간 데이터 분포의 모양은 동질적이다. ---> t.test()
# 대립가설: 두 그룹간 데이터 분포의 모양은 동질적이지 않다. ---> wilcox.test()

t.test(result$before, result$after, paired = TRUE)
1
2
3
4
5
6
7
8
9
10
11
## 
## Paired t-test
##
## data: result$before and result$after
## t = -13.642, df = 95, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -1.205184 -0.898983
## sample estimates:
## mean of the differences
## -1.052083
1
2
3
4
# p-value값은 유의수준 0.05보다 매우 작기 때문에 귀무가설을 기각하고 대립가설을 채택한다, 즉, 두 집단 간의 평균에 차이가 있는 것으로 나타났다. 

# 방향성을 갖는 단측 검정을 실시한다.
t.test(result$before, result$after, paired = TRUE, alter = "greater", conf.level = 0.95, conf.int = TRUE)
1
2
3
4
5
6
7
8
9
10
11
## 
## Paired t-test
##
## data: result$before and result$after
## t = -13.642, df = 95, p-value = 1
## alternative hypothesis: true difference in means is greater than 0
## 95 percent confidence interval:
## -1.180182 Inf
## sample estimates:
## mean of the differences
## -1.052083
1
2
# 귀무가설: result$after의 평균 점수가 result$before의 평균 점수보다 크다
# 대립가설: result$after의 평균 점수가 result$before의 평균 점수보다 크지 않다.

#유의확률이 1, 즉 귀무가설을 기각할 수 없다, result$after의 평균 점수가 result$before의 평균 점수보다 크다.

빅데이터 시각화 0323

문제 1. 패키지 설치 방법 MD

1
2
library(ggplot2)
library(dplyr)
1
2
## 
## Attaching package: 'dplyr'
1
2
3
## The following objects are masked from 'package:stats':
##
## filter, lag
1
2
3
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union

문제 2. 질적 변수와 양적 병수의 차이에 대해 설명하시오

질적 변수는 어떠한 카테고리내에서 다양하게 모이는 변수이고, 양적 변수는 크기를 숫자로 나타내어 유의미한 가치를 가지는 변수입니다.

문제 3. 엑셀 데이터를 불러오세요

1
2
3
library(dplyr)
counties<-readxl::read_xlsx("1_day/docs/counties.xslx",sheet=1)
glimpse(counties)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
## Rows: 3,138
## Columns: 40
## $ census_id <chr> "1001", "1003", "1005", "1007", "1009", "1011", "10~
## $ state <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabam~
## $ county <chr> "Autauga", "Baldwin", "Barbour", "Bibb", "Blount", ~
## $ region <chr> "South", "South", "South", "South", "South", "South~
## $ metro <chr> "Metro", "Metro", "Nonmetro", "Metro", "Metro", "No~
## $ population <dbl> 55221, 195121, 26932, 22604, 57710, 10678, 20354, 1~
## $ men <dbl> 26745, 95314, 14497, 12073, 28512, 5660, 9502, 5627~
## $ women <dbl> 28476, 99807, 12435, 10531, 29198, 5018, 10852, 603~
## $ hispanic <dbl> 2.6, 4.5, 4.6, 2.2, 8.6, 4.4, 1.2, 3.5, 0.4, 1.5, 7~
## $ white <dbl> 75.8, 83.1, 46.2, 74.5, 87.9, 22.2, 53.3, 73.0, 57.~
## $ black <dbl> 18.5, 9.5, 46.7, 21.4, 1.5, 70.7, 43.8, 20.3, 40.3,~
## $ native <dbl> 0.4, 0.6, 0.2, 0.4, 0.3, 1.2, 0.1, 0.2, 0.2, 0.6, 0~
## $ asian <dbl> 1.0, 0.7, 0.4, 0.1, 0.1, 0.2, 0.4, 0.9, 0.8, 0.3, 0~
## $ pacific <dbl> 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0~
## $ citizens <dbl> 40725, 147695, 20714, 17495, 42345, 8057, 15581, 88~
## $ income <dbl> 51281, 50254, 32964, 38678, 45813, 31938, 32229, 41~
## $ income_err <dbl> 2391, 1263, 2973, 3995, 3141, 5884, 1793, 925, 2949~
## $ income_per_cap <dbl> 24974, 27317, 16824, 18431, 20532, 17580, 18390, 21~
## $ income_per_cap_err <dbl> 1080, 711, 798, 1618, 708, 2055, 714, 489, 1366, 15~
## $ poverty <dbl> 12.9, 13.4, 26.7, 16.8, 16.7, 24.6, 25.4, 20.5, 21.~
## $ child_poverty <dbl> 18.6, 19.2, 45.3, 27.9, 27.2, 38.4, 39.2, 31.6, 37.~
## $ professional <dbl> 33.2, 33.1, 26.8, 21.5, 28.5, 18.8, 27.5, 27.3, 23.~
## $ service <dbl> 17.0, 17.7, 16.1, 17.9, 14.1, 15.0, 16.6, 17.7, 14.~
## $ office <dbl> 24.2, 27.1, 23.1, 17.8, 23.9, 19.7, 21.9, 24.2, 26.~
## $ construction <dbl> 8.6, 10.8, 10.8, 19.0, 13.5, 20.1, 10.3, 10.5, 11.5~
## $ production <dbl> 17.1, 11.2, 23.1, 23.7, 19.9, 26.4, 23.7, 20.4, 24.~
## $ drive <dbl> 87.5, 84.7, 83.8, 83.2, 84.9, 74.9, 84.5, 85.3, 85.~
## $ carpool <dbl> 8.8, 8.8, 10.9, 13.5, 11.2, 14.9, 12.4, 9.4, 11.9, ~
## $ transit <dbl> 0.1, 0.1, 0.4, 0.5, 0.4, 0.7, 0.0, 0.2, 0.2, 0.2, 0~
## $ walk <dbl> 0.5, 1.0, 1.8, 0.6, 0.9, 5.0, 0.8, 1.2, 0.3, 0.6, 1~
## $ other_transp <dbl> 1.3, 1.4, 1.5, 1.5, 0.4, 1.7, 0.6, 1.2, 0.4, 0.7, 1~
## $ work_at_home <dbl> 1.8, 3.9, 1.6, 0.7, 2.3, 2.8, 1.7, 2.7, 2.1, 2.5, 1~
## $ mean_commute <dbl> 26.5, 26.4, 24.1, 28.8, 34.9, 27.5, 24.6, 24.1, 25.~
## $ employed <dbl> 23986, 85953, 8597, 8294, 22189, 3865, 7813, 47401,~
## $ private_work <dbl> 73.6, 81.5, 71.8, 76.8, 82.0, 79.5, 77.4, 74.1, 85.~
## $ public_work <dbl> 20.9, 12.3, 20.8, 16.1, 13.5, 15.1, 16.2, 20.8, 12.~
## $ self_employed <dbl> 5.5, 5.8, 7.3, 6.7, 4.2, 5.4, 6.2, 5.0, 2.8, 7.9, 4~
## $ family_work <dbl> 0.0, 0.4, 0.1, 0.4, 0.4, 0.0, 0.2, 0.1, 0.0, 0.5, 0~
## $ unemployment <dbl> 7.6, 7.5, 17.6, 8.3, 7.7, 18.0, 10.9, 12.3, 8.9, 7.~
## $ land_area <dbl> 594.44, 1589.78, 884.88, 622.58, 644.78, 622.81, 77~

문제 4. private_work, unemployment를 활용하여 산점도를 작성하세요.

1
2
3
4
5
6
7
library(dplyr)
counties<-readxl::read_xlsx("1_day/docs/counties.xslx",sheet=1)

library(ggplot2)
ggplot(counties,aes(x=private_work,y=unemployment))+geom_point(aes(colour=region))->g1

plot(g1)

문제 5. dplyr 함수를 활용하여, 아래 데이터를 요약하세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
## Rows: 3,138
## Columns: 40
## $ census_id <chr> "1001", "1003", "1005", "1007", "1009", "1011", "10~
## $ state <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabam~
## $ county <chr> "Autauga", "Baldwin", "Barbour", "Bibb", "Blount", ~
## $ region <chr> "South", "South", "South", "South", "South", "South~
## $ metro <chr> "Metro", "Metro", "Nonmetro", "Metro", "Metro", "No~
## $ population <dbl> 55221, 195121, 26932, 22604, 57710, 10678, 20354, 1~
## $ men <dbl> 26745, 95314, 14497, 12073, 28512, 5660, 9502, 5627~
## $ women <dbl> 28476, 99807, 12435, 10531, 29198, 5018, 10852, 603~
## $ hispanic <dbl> 2.6, 4.5, 4.6, 2.2, 8.6, 4.4, 1.2, 3.5, 0.4, 1.5, 7~
## $ white <dbl> 75.8, 83.1, 46.2, 74.5, 87.9, 22.2, 53.3, 73.0, 57.~
## $ black <dbl> 18.5, 9.5, 46.7, 21.4, 1.5, 70.7, 43.8, 20.3, 40.3,~
## $ native <dbl> 0.4, 0.6, 0.2, 0.4, 0.3, 1.2, 0.1, 0.2, 0.2, 0.6, 0~
## $ asian <dbl> 1.0, 0.7, 0.4, 0.1, 0.1, 0.2, 0.4, 0.9, 0.8, 0.3, 0~
## $ pacific <dbl> 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0~
## $ citizens <dbl> 40725, 147695, 20714, 17495, 42345, 8057, 15581, 88~
## $ income <dbl> 51281, 50254, 32964, 38678, 45813, 31938, 32229, 41~
## $ income_err <dbl> 2391, 1263, 2973, 3995, 3141, 5884, 1793, 925, 2949~
## $ income_per_cap <dbl> 24974, 27317, 16824, 18431, 20532, 17580, 18390, 21~
## $ income_per_cap_err <dbl> 1080, 711, 798, 1618, 708, 2055, 714, 489, 1366, 15~
## $ poverty <dbl> 12.9, 13.4, 26.7, 16.8, 16.7, 24.6, 25.4, 20.5, 21.~
## $ child_poverty <dbl> 18.6, 19.2, 45.3, 27.9, 27.2, 38.4, 39.2, 31.6, 37.~
## $ professional <dbl> 33.2, 33.1, 26.8, 21.5, 28.5, 18.8, 27.5, 27.3, 23.~
## $ service <dbl> 17.0, 17.7, 16.1, 17.9, 14.1, 15.0, 16.6, 17.7, 14.~
## $ office <dbl> 24.2, 27.1, 23.1, 17.8, 23.9, 19.7, 21.9, 24.2, 26.~
## $ construction <dbl> 8.6, 10.8, 10.8, 19.0, 13.5, 20.1, 10.3, 10.5, 11.5~
## $ production <dbl> 17.1, 11.2, 23.1, 23.7, 19.9, 26.4, 23.7, 20.4, 24.~
## $ drive <dbl> 87.5, 84.7, 83.8, 83.2, 84.9, 74.9, 84.5, 85.3, 85.~
## $ carpool <dbl> 8.8, 8.8, 10.9, 13.5, 11.2, 14.9, 12.4, 9.4, 11.9, ~
## $ transit <dbl> 0.1, 0.1, 0.4, 0.5, 0.4, 0.7, 0.0, 0.2, 0.2, 0.2, 0~
## $ walk <dbl> 0.5, 1.0, 1.8, 0.6, 0.9, 5.0, 0.8, 1.2, 0.3, 0.6, 1~
## $ other_transp <dbl> 1.3, 1.4, 1.5, 1.5, 0.4, 1.7, 0.6, 1.2, 0.4, 0.7, 1~
## $ work_at_home <dbl> 1.8, 3.9, 1.6, 0.7, 2.3, 2.8, 1.7, 2.7, 2.1, 2.5, 1~
## $ mean_commute <dbl> 26.5, 26.4, 24.1, 28.8, 34.9, 27.5, 24.6, 24.1, 25.~
## $ employed <dbl> 23986, 85953, 8597, 8294, 22189, 3865, 7813, 47401,~
## $ private_work <dbl> 73.6, 81.5, 71.8, 76.8, 82.0, 79.5, 77.4, 74.1, 85.~
## $ public_work <dbl> 20.9, 12.3, 20.8, 16.1, 13.5, 15.1, 16.2, 20.8, 12.~
## $ self_employed <dbl> 5.5, 5.8, 7.3, 6.7, 4.2, 5.4, 6.2, 5.0, 2.8, 7.9, 4~
## $ family_work <dbl> 0.0, 0.4, 0.1, 0.4, 0.4, 0.0, 0.2, 0.1, 0.0, 0.5, 0~
## $ unemployment <dbl> 7.6, 7.5, 17.6, 8.3, 7.7, 18.0, 10.9, 12.3, 8.9, 7.~
## $ land_area <dbl> 594.44, 1589.78, 884.88, 622.58, 644.78, 622.81, 77~
1
## `summarise()` has grouped output by 'region'. You can override using the `.groups` argument.
1
2
3
4
5
6
7
## Rows: 50
## Columns: 4
## Groups: region [4]
## $ region <chr> "North Central", "North Central", "North Central", "North Ce~
## $ state <chr> "Illinois", "Indiana", "Iowa", "Kansas", "Michigan", "Minnes~
## $ sum_men <dbl> 6316899, 3235263, 1534595, 1439862, 4861973, 2692166, 296400~
## $ sum_women <dbl> 6556862, 3333382, 1558931, 1453125, 5038598, 2727005, 308144~

문제 6. final_df를 기준으로 막대 그래프를 그립니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
## Rows: 3,138
## Columns: 40
## $ census_id <chr> "1001", "1003", "1005", "1007", "1009", "1011", "10~
## $ state <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabam~
## $ county <chr> "Autauga", "Baldwin", "Barbour", "Bibb", "Blount", ~
## $ region <chr> "South", "South", "South", "South", "South", "South~
## $ metro <chr> "Metro", "Metro", "Nonmetro", "Metro", "Metro", "No~
## $ population <dbl> 55221, 195121, 26932, 22604, 57710, 10678, 20354, 1~
## $ men <dbl> 26745, 95314, 14497, 12073, 28512, 5660, 9502, 5627~
## $ women <dbl> 28476, 99807, 12435, 10531, 29198, 5018, 10852, 603~
## $ hispanic <dbl> 2.6, 4.5, 4.6, 2.2, 8.6, 4.4, 1.2, 3.5, 0.4, 1.5, 7~
## $ white <dbl> 75.8, 83.1, 46.2, 74.5, 87.9, 22.2, 53.3, 73.0, 57.~
## $ black <dbl> 18.5, 9.5, 46.7, 21.4, 1.5, 70.7, 43.8, 20.3, 40.3,~
## $ native <dbl> 0.4, 0.6, 0.2, 0.4, 0.3, 1.2, 0.1, 0.2, 0.2, 0.6, 0~
## $ asian <dbl> 1.0, 0.7, 0.4, 0.1, 0.1, 0.2, 0.4, 0.9, 0.8, 0.3, 0~
## $ pacific <dbl> 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0~
## $ citizens <dbl> 40725, 147695, 20714, 17495, 42345, 8057, 15581, 88~
## $ income <dbl> 51281, 50254, 32964, 38678, 45813, 31938, 32229, 41~
## $ income_err <dbl> 2391, 1263, 2973, 3995, 3141, 5884, 1793, 925, 2949~
## $ income_per_cap <dbl> 24974, 27317, 16824, 18431, 20532, 17580, 18390, 21~
## $ income_per_cap_err <dbl> 1080, 711, 798, 1618, 708, 2055, 714, 489, 1366, 15~
## $ poverty <dbl> 12.9, 13.4, 26.7, 16.8, 16.7, 24.6, 25.4, 20.5, 21.~
## $ child_poverty <dbl> 18.6, 19.2, 45.3, 27.9, 27.2, 38.4, 39.2, 31.6, 37.~
## $ professional <dbl> 33.2, 33.1, 26.8, 21.5, 28.5, 18.8, 27.5, 27.3, 23.~
## $ service <dbl> 17.0, 17.7, 16.1, 17.9, 14.1, 15.0, 16.6, 17.7, 14.~
## $ office <dbl> 24.2, 27.1, 23.1, 17.8, 23.9, 19.7, 21.9, 24.2, 26.~
## $ construction <dbl> 8.6, 10.8, 10.8, 19.0, 13.5, 20.1, 10.3, 10.5, 11.5~
## $ production <dbl> 17.1, 11.2, 23.1, 23.7, 19.9, 26.4, 23.7, 20.4, 24.~
## $ drive <dbl> 87.5, 84.7, 83.8, 83.2, 84.9, 74.9, 84.5, 85.3, 85.~
## $ carpool <dbl> 8.8, 8.8, 10.9, 13.5, 11.2, 14.9, 12.4, 9.4, 11.9, ~
## $ transit <dbl> 0.1, 0.1, 0.4, 0.5, 0.4, 0.7, 0.0, 0.2, 0.2, 0.2, 0~
## $ walk <dbl> 0.5, 1.0, 1.8, 0.6, 0.9, 5.0, 0.8, 1.2, 0.3, 0.6, 1~
## $ other_transp <dbl> 1.3, 1.4, 1.5, 1.5, 0.4, 1.7, 0.6, 1.2, 0.4, 0.7, 1~
## $ work_at_home <dbl> 1.8, 3.9, 1.6, 0.7, 2.3, 2.8, 1.7, 2.7, 2.1, 2.5, 1~
## $ mean_commute <dbl> 26.5, 26.4, 24.1, 28.8, 34.9, 27.5, 24.6, 24.1, 25.~
## $ employed <dbl> 23986, 85953, 8597, 8294, 22189, 3865, 7813, 47401,~
## $ private_work <dbl> 73.6, 81.5, 71.8, 76.8, 82.0, 79.5, 77.4, 74.1, 85.~
## $ public_work <dbl> 20.9, 12.3, 20.8, 16.1, 13.5, 15.1, 16.2, 20.8, 12.~
## $ self_employed <dbl> 5.5, 5.8, 7.3, 6.7, 4.2, 5.4, 6.2, 5.0, 2.8, 7.9, 4~
## $ family_work <dbl> 0.0, 0.4, 0.1, 0.4, 0.4, 0.0, 0.2, 0.1, 0.0, 0.5, 0~
## $ unemployment <dbl> 7.6, 7.5, 17.6, 8.3, 7.7, 18.0, 10.9, 12.3, 8.9, 7.~
## $ land_area <dbl> 594.44, 1589.78, 884.88, 622.58, 644.78, 622.81, 77~
1
## `summarise()` has grouped output by 'region'. You can override using the `.groups` argument.
1
2
3
4
5
6
## Rows: 12
## Columns: 3
## Groups: region [1]
## $ region <chr> "North Central", "North Central", "North Central", "North Cent~
## $ state <chr> "Illinois", "Indiana", "Iowa", "Kansas", "Michigan", "Minnesot~
## $ sum_pop <dbl> 12873761, 6568645, 3093526, 2892987, 9900571, 5419171, 6045448~

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Hello World

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

0322_KORIT

1. 블로그 관리

-blog 포스트나 내용을 추가 수정했을때는
#hexo generate
-제대로 동작하는지 임시 서버로 확인
#hexo server
-확인 후 배포
#hexo deploy

오류 1 : ggaggu.github.io 레파지토리를 제대로 생성하지않아서 404 NOT FOUND
오류 2: config_의 url은 https://주소

-포스트 작성하기

1
2
1) hexo new [theme]<title>
2) hexo new (post: 디폴트라 안적어도됨) temp.md

2. R 언어

R은 통계분석하기 좋은 언어
*초보자가 입문하기 굉장히 좋은 언어. *
*데이터를 어떻게 시각화할지 가이드라인이 잘 나와있다. *

  1. 기본 문법

변수 <- 42: 자료형이 숫자
변수 <- “char” :자료형이 문자. ===> 자료형 자동으로 판별됨
class(변수) ===> 이 변수의 자료형을 출력한다.

2) 벡터
변수<-c(1,2,3)==> 이 변수를 벡터로 선언한다. 이 벡터는 하나의 자료형을 가짐
만약 전부 다른 자료형일때, 우선순위대로 변환시킨다.
*논리형<숫자형<문자형 *

3)factor **
어떤 자료형이든 통계적으로 분석 할 수 있게 해주는 문법

1
2
factor_location <- factor(location)
===> factor_loaction의 Levels: 부산 서울 인천

우선순위를 정할 수 도 있다.

1
2
3
factor_location<-factor(location, ordered=TRUE, levels=c("서울","인천","부산"))
===> factor location의 levels"서울"<"인천"<"부산"

4) ggplot*

  • 1단계 : 패키지 불러오기

    1
    2
    install.packages("ggplot2") #gglot 패키지 설치
    library(ggplot2)
  • 2단계 : 데이터 불러오기 및 확인

    1
    2
    data("데이터")
    str("데이터")
  • 3단계 : 가공되지 않은 데이터 가공하기(시각화 위해)

  • 4단계 : 시각화 하기

    1
    2
    ggplot(data=iris, mapping=aes(x=x축이름, y=y축 이름))+geom_point() + ... ...... 
    #ggplot의 장점은 레이어 형식이란것과 틀이 주어져있다는 것. +를 사용하여 뒤에 계속 붙일수있다는게 장점이다.

    참고 링크:
    50개의 ggplot 틀

#심화 예제는 티스토리에 따로 포스팅.

0319_KORIT

1. GIT 설치

-git config – global user.email rksl32@naver.com (깃이메일)
-git config – global user.name ggaggu (깃이름)
-git init
-git add .
-git commit -m “커밋 이름”
-git push

2. pycharm 세팅

[사진은 pycharm에서]

3. git blog 생성

이것은 추후 따로 게시할 예정.

[사진 여러장]

You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.