[14-02-04]

3.1 들어가며

3.2 단정한 데이터 tidy data

시각화를 해보자

library(reshape2)  # 먼저 미러사이트에서 패키지설치는 기본! 당연하다.
library(data.table)  # .RData파일을 불러오기 위해 변환해야한다
setwd("C:/Users/Byeongsoo/Documents/R")
load("pew.RData")
pew <- as.data.table(raw)
head(pew)
##              religion <$10k $10-20k $20-30k $30-40k $40-50k $50-75k
## 1:           Agnostic    27      34      60      81      76     137
## 2:            Atheist    12      27      37      52      35      70
## 3:           Buddhist    27      21      30      34      33      58
## 4:           Catholic   418     617     732     670     638    1116
## 5: Don't know/refused    15      14      15      11      10      35
## 6:   Evangelical Prot   575     869    1064     982     881    1486
##    $75-100k $100-150k >150k Don't know/refused
## 1:      122       109    84                 96
## 2:       73        59    74                 76
## 3:       62        39    53                 54
## 4:      949       792   633               1489
## 5:       21        17    18                116
## 6:      949       723   414               1529
melted <- melt(pew, measure.vars = c(2, 3, 4, 5, 6, 7), variable.name = "income", 
    value.name = "freq")
head(melted)
##             religion $75-100k $100-150k >150k Don't know/refused income
## 1           Agnostic      122       109    84                 96  <$10k
## 2            Atheist       73        59    74                 76  <$10k
## 3           Buddhist       62        39    53                 54  <$10k
## 4           Catholic      949       792   633               1489  <$10k
## 5 Don't know/refused       21        17    18                116  <$10k
## 6   Evangelical Prot      949       723   414               1529  <$10k
##   freq
## 1   27
## 2   12
## 3   27
## 4  418
## 5   15
## 6  575

pew데이터는 사이트에서 받는다. (이건 개인적인 공부용도이므로 공개를 할 수는 없다….)
melt를 사용한 이후는 후에 dcast를 사용할 때, dcast가 molten데이터 프레임을 인자로 받기 때문이다.
measure.vars는 데이터를 melt할 때 사용할 변수들이고, variable.name은 그 변수들의 이름이고, value.name은 variable.name에서 선언한 변수들에 대응하는 값을 저장할 름이다.

막대그래프를 그려보자.

물론 ggplot2는 “단정한 데이터"를 입력해야 하는 특징 있다.

library(ggplot2)
ggplot(melted, aes(religion, freq)) + geom_bar(aes(fill = income), stat = "identity") + 
    theme(axis.text.x = element_text(angle = 45))

plot of chunk unnamed-chunk-2

  1. ggplot 함수를 사용해 축을 만든다. x축은 religion, y축은 freq
  2. gemo_bar함수는 막대그래프를 만든다.
    If you want the heights of the bars to represent values in the data, use stat="identity” and map a value to the y aesthetic. 그러나,
    By default, geom_bar uses stat=“bin”. This makes the height of each bar equal to the number of cases in each group, and it is incompatible with mapping values to the y aesthetic.
  3. theme에서 x축의 항목들의 이름을 45도 움직인다.

종교별 소득 분포를 절대적인 빈도수로 비교할 수 있지만,
몇몇 종교의 모수가 너무 적어서 소득 분포가 어떻게 되는지 구분하기 쉽지 않다.

library(plyr)
melted <- ddply(melted, .(religion), mutate, freq_sum = sum(freq))
head(melted)
##   religion $75-100k $100-150k >150k Don't know/refused  income freq
## 1 Agnostic      122       109    84                 96   <$10k   27
## 2 Agnostic      122       109    84                 96 $10-20k   34
## 3 Agnostic      122       109    84                 96 $20-30k   60
## 4 Agnostic      122       109    84                 96 $30-40k   81
## 5 Agnostic      122       109    84                 96 $40-50k   76
## 6 Agnostic      122       109    84                 96 $50-75k  137
##   freq_sum
## 1      415
## 2      415
## 3      415
## 4      415
## 5      415
## 6      415
melted_freq <- ddply(melted, .(religion, income), summarise, freq_precent = freq/freq_sum)

ddply()는 인자로 데이터, 데이터를 그룹 지을 변수명, 데이터 처리에 사용할 함수를 받는다.
mutate는 새로운 칼럼을 만들어 새로운 변수의 값을 넣을 수 있게 한다.
summarise는 두번째 인자에 따라서, 새로운 데이터 프레임을 만든다.

ggplot(melted_freq, aes(religion, freq_precent)) + geom_bar(aes(fill = income), 
    stat = "identity") + theme(axis.text.x = element_text(angle = 45))

plot of chunk unnamed-chunk-4

다음의 단 한 줄의 코드로 슬라이드 발표를 위한, 데이터 “pew"와 같은 데이터 형태로 변환할 수도 있다.

dcast(melted_freq, religion ~ income, value.var = "freq_precent")
##                   religion   <$10k $10-20k $20-30k $30-40k $40-50k $50-75k
## 1                 Agnostic 0.06506 0.08193 0.14458  0.1952 0.18313  0.3301
## 2                  Atheist 0.05150 0.11588 0.15880  0.2232 0.15021  0.3004
## 3                 Buddhist 0.13300 0.10345 0.14778  0.1675 0.16256  0.2857
## 4                 Catholic 0.09974 0.14722 0.17466  0.1599 0.15223  0.2663
## 5       Don't know/refused 0.15000 0.14000 0.15000  0.1100 0.10000  0.3500
## 6         Evangelical Prot 0.09817 0.14837 0.18166  0.1677 0.15042  0.2537
## 7                    Hindu 0.01408 0.12676 0.09859  0.1268 0.15493  0.4789
## 8  Historically Black Prot 0.16691 0.17862 0.17277  0.1742 0.14422  0.1633
## 9        Jehovah's Witness 0.13699 0.18493 0.16438  0.1644 0.14384  0.2055
## 10                  Jewish 0.08920 0.08920 0.11737  0.1174 0.14085  0.4460
## 11           Mainline Prot 0.07573 0.12972 0.16221  0.1716 0.17060  0.2901
## 12                  Mormon 0.08631 0.11905 0.14286  0.1518 0.16667  0.3333
## 13                  Muslim 0.09375 0.10938 0.14062  0.1562 0.14062  0.3594
## 14                Orthodox 0.07927 0.10366 0.14024  0.1951 0.19512  0.2866
## 15         Other Christian 0.13433 0.10448 0.16418  0.1940 0.19403  0.2090
## 16            Other Faiths 0.07968 0.13147 0.15936  0.1833 0.19522  0.2510
## 17   Other World Religions 0.21739 0.08696 0.13043  0.1739 0.08696  0.3043
## 18            Unaffiliated 0.10217 0.14077 0.17608  0.1718 0.16055  0.2486

dcast는 melt된 데이터 프레임을 인자로 받는다.
religion에 따른 income을 보여준다.