25. R을 이용한 범주형 자료 요약
Chapter 25. R을 이용한 범주형 자료 요약
지난 회차에 범주형 자료 요약에 대해 알아봤습니다.
지난 회차에서 살펴봤던 스마트폰 모델 선호도 자료를 R을 이용하여 분할표와 그래프를 그려보겠습니다.
◈ 예제 : 세 가지 스마트폰 모델에 대한 남녀별로 선호도 비교
1. 자료 불러오기
위 자료는 CSV(Comma-Separated Value) 파일로 이루어져 있습니다.
R에서는 파일의 종류에 따라 불러들이는 함수가 따로 있습니다.
CSV 파일을 불러오는 함수는 read.csv( ) 입니다.
smart <- read.csv("smart.csv", header = TRUE, fileEncoding = "CP949", encoding = "UTF-8")
head(smart)
gender model
1 남자 A
2 남자 A
3 남자 B
4 남자 B
5 남자 A
6 남자 A
head( ) 함수는 데이터의 처음 6개의 행을 나타냅니다.
read.csv( "파일이름.csv") 처럼 파일이름으로 했을 때 에러가 난다면, header = TRUE, fileEncoding = "CP949", encoding = "UTF-8" 등의 파라미터를 같이 사용해 주면 잘 불러들일 수 있습니다.
2. 분할표(Contingency Table)
분할표를 작성할 때 사용하는 함수는 table( ) 입니다. 이 함수는 지난 도수분포표 작성에도 사용했습니다.
다만, 분할표는 두 개 이상의 변수이기 때문에 입력값이 두 개 이상입니다.
table(gender,model)
이렇게 단순히 컬럼이름만으로는 에러가 발생합니다.
(1) "$" 사용하기
table(smart$gender,smart$model)
A B C
남자 35 23 18
여자 17 33 20
▶ "$" 은 데이터프레임에서 특정열을 선택하기 위해 사용하는 연산자입니다.
smart$gender 는 smart 데이터 프레임 안에 있는 gender 열을 의미합니다.
(2) with( ) 함수 사용하기
with(smart,table(gender,model))
model
gender A B C
남자 35 23 18
여자 17 33 20
▶with( ) 함수는 데이터 프레임 내의 변수에 대해 작업할 때 유용하게 사용되는 함수이며, 변수 이름을 반복해서 쓰지않고 간결하게 코드를 작성할 수 있습니다.
with(data,expr)
data : 데이터 프레임을 나타내는 객체
expr : 데이터 프레임 내의 변수애 대해 실행할 R 함수 혹은 표현식 -> 여기서는 table( ) 함수 사용
(3) attach( ) 함수 사용하기
attach(smart)
table(gender,model)
detach(smart)
model
gender A B C
남자 35 23 18
여자 17 33 20
3. 합계 구하기
(1) 전체 합계
margin.table( ) 함수는 table( ) 함수로 생성된 도수분포표를 기반으로, 행과 열의 합계를 계산하여 반환하는 합수입니다. 도수분포표의 모든 차원에 대한 합계를 계산합니다.
smartable <-table(smart$gender,smart$model)
margin.table(smartable)
146
(2) 행 (Row) 기준 합계
margin.table(smartable,margin=1)
남자 여자
76 70
행 기준인 남자, 여자 별 합계를 나타냅니다.
(3) 열 (Column) 기준 합계
margin.table(smartable,margin=2)
A B C
52 56 38
열 기준인 모델 A, B, C 별 합계를 나타냅니다.
4. 상대도수(비율) 구하기
(1) 전체 합계 기준
prop.table( ) 함수는 table( ) 함수로 생성된 도수분포표의 비율을 계산하는 함수입니다. 전체 합이 1이 되도록 도수분포표의 값을 나누어줍니다.
prop.table(smartable)
A B C
남자 0.2397260 0.1575342 0.1232877
여자 0.1164384 0.2260274 0.1369863
분모는 전체 합계인 146을 기준으로 작성된 것입니다.
(2) 행 (Row) 기준
prop.table(smartable, margin = 1)
A B C
남자 0.4605263 0.3026316 0.2368421
여자 0.2428571 0.4714286 0.2857143
분모는 남자 합계 76, 여자 합계 70 을 기준으로 작성되었습니다.
(3) 열(Column) 기준
prop.table(smartable, margin = 2)
A B C
남자 0.4605263 0.3026316 0.2368421
여자 0.2428571 0.4714286 0.2857143
분모는 A 52, B 56, C 38 을 기준으로 작성되었습니다.
5. 그래프로 표현하기
유의미한 분석 결과를 보여주는 행 기준 상대도수를 그래프로 표현해보겠습니다.
(1) 남성이 선호하는 모델 분석
props <- prop.table(smartable, margin = 1)
props <- round(props*100,1)
male <-props[1,]
label_0 <- c("A","B","C")
label_m <- paste(label_0, " (", male, "%)", sep = "")
par(mfrow=c(1,2))
pie(male,label_m, col=c("purple","yellow","green"))
barplot(male, ylim = c(0,50) ,space = 0.3, col=c("purple","yellow","green"))
abline(h=0)
abline(h=c(10,30,50),lty=2)
props <- prop.table(smartable, margin = 1)
props <- round(props*100,1)
male <-props[1,]
아래는 앞에 구했던 행기준 데이터 프레임 입니다.
A B C
남자 0.4605263 0.3026316 0.2368421
여자 0.2428571 0.4714286 0.2857143
이 데이터를 round( ) 함수를 이용해 보기 좋게 소숫점 자리를 정리합니다.
props 란 데이터 프레임을 만들고, 남성의 자료는 첫째줄만 따로 객체로 만듭니다.
"데이터 프레임 [ 1, ]" 은 첫번째 줄을 반환합니다. 반환된 자료를 male이란 이름으로 저장합니다.
label_0 <- c("A","B","C")
label_m <- paste(label_0, " (", male, "%)", sep = "")
par(mfrow=c(1,2))
pie(male,label_m, col=c("purple","yellow","green"))
파이차트를 그리기 위한 코드 입니다.
pie( ) 함수는 pie(value,label) 로 value에는 데이터 값이, label에는 데이터 이름이 들어가는 구조입니다.
paste( ) 함수를 사용하여 값에 "%" 기호를 붙이고 label_m 이란 이름으로 저장합니다.
(2) 여성이 선호하는 모델 분석
female <-props[2,]
label_f <- paste(label_0, " (", female, "%)", sep = "")
par(mfrow=c(1,2))
pie(female,label_m, col=c("purple","yellow","green"))
barplot(female, ylim = c(0,50) ,space = 0.3, col=c("purple","yellow","green"))
abline(h=0)
abline(h=c(10,30,50),lty=2)
props[2,] 는 두번째 줄 데이터를 반환합니다. 이를 female이란 이름으로 저장하고, 앞선 코드에서 male 위치를 female로 바꿔줍니다. 그런 후 실행하면 손쉽게 여성의 자료도 얻을 수 있습니다.
정리
# 1. 자료불러오기
smart <- read.csv("smart.csv", header = TRUE, fileEncoding = "CP949", encoding = "UTF-8")
head(smart)
# 2. 분할표
smartable <-table(smart$gender,smart$model)
with(smart,table(gender,model))
attach(smart)
table(gender,model)
detach(smart)
# 3. 합계
smartable <-table(smart$gender,smart$model)
margin.table(smartable)
margin.table(smartable,margin=1)
margin.table(smartable,margin=2)
# 4. 상대도수
prop.table(smartable)
prop.table(smartable, margin = 1)
prop.table(smartable, margin = 2)
# 5.그래프 그리기
props <- prop.table(smartable, margin = 1)
props <- round(props*100,1)
male <-props[1,]
label_0 <- c("A","B","C")
label_m <- paste(label_0, " (", male, "%)", sep = "")
par(mfrow=c(1,2))
pie(male,label_m, col=c("purple","yellow","green"))
barplot(male, ylim = c(0,50) ,space = 0.3, col=c("purple","yellow","green"))
abline(h=0)
abline(h=c(10,30,50),lty=2)
female <-props[2,]
label_f <- paste(label_0, " (", female, "%)", sep = "")
par(mfrow=c(1,2))
pie(female,label_f, col=c("purple","yellow","green"))
barplot(female, ylim = c(0,50) ,space = 0.3, col=c("purple","yellow","green"))
abline(h=0)
abline(h=c(10,30,50),lty=2)