1. R 기초 활용

#install.packages("dplyr")
#install.packages("ggplot2")
#install.packages("ggthemes")
#install.packages("stringr")
#install.packages("tidyr")

library(dplyr)
library(ggplot2)
library(ggthemes)
library(stringr)
library(tidyr)
getwd()
## [1] "D:/data_analysis/study"
setwd("D:/data_analysis/study")
data <- read.csv("example_population_f.csv", header = TRUE)
head(data)
##   X  Provinces      City Population Households PersInHou   Male Female
## 1 2 서울특별시   종로구      155695      72882      2.14  76962  78733
## 2 3 서울특별시     중구      126817      59614      2.13  63292  63525
## 3 4 서울특별시   용산구      235186     108138      2.17 114119 121067
## 4 5 서울특별시   성동구      298145     126915      2.35 148265 149880
## 5 6 서울특별시   광진구      362197     158769      2.28 177946 184251
## 6 7 서울특별시 동대문구      362604     160110      2.26 181825 180779
##   SexRatio
## 1     0.98
## 2     1.00
## 3     0.94
## 4     0.99
## 5     0.97
## 6     1.01
str(data)
## 'data.frame':    263 obs. of  9 variables:
##  $ X         : int  2 3 4 5 6 7 8 9 10 11 ...
##  $ Provinces : Factor w/ 16 levels "강원도","경기도",..: 9 9 9 9 9 9 9 9 9 9 ...
##  $ City      : Factor w/ 240 levels "가평군 ","강남구 ",..: 187 188 157 104 31 64 189 105 5 62 ...
##  $ Population: int  155695 126817 235186 298145 362197 362604 417976 464176 333523 353284 ...
##  $ Households: int  72882 59614 108138 126915 158769 160110 177077 192670 141325 137260 ...
##  $ PersInHou : num  2.14 2.13 2.17 2.35 2.28 2.26 2.36 2.41 2.36 2.57 ...
##  $ Male      : int  76962 63292 114119 148265 177946 181825 208657 227676 164304 174075 ...
##  $ Female    : int  78733 63525 121067 149880 184251 180779 209319 236500 169219 179209 ...
##  $ SexRatio  : num  0.98 1 0.94 0.99 0.97 1.01 1 0.96 0.97 0.97 ...
summary(data)
##        X              Provinces       City       Population     
##  Min.   :  2.0   경기도    :51   동구   :  6   Min.   :  10304  
##  1st Qu.: 72.5   경상북도  :25   중구   :  6   1st Qu.:  63302  
##  Median :143.0   서울특별시:25   남구   :  5   Median : 184992  
##  Mean   :142.3   경상남도  :23   서구   :  5   Mean   : 232765  
##  3rd Qu.:212.5   전라남도  :22   북구   :  4   3rd Qu.: 341550  
##  Max.   :281.0   강원도    :18   강서구 :  2   Max.   :1177851  
##                  (Other)   :99   (Other):235                    
##    Households       PersInHou          Male            Female      
##  Min.   :  5365   Min.   :1.860   Min.   :  5518   Min.   :  4786  
##  1st Qu.: 28785   1st Qu.:2.170   1st Qu.: 31671   1st Qu.: 32096  
##  Median : 74214   Median :2.370   Median : 93176   Median : 91925  
##  Mean   : 93816   Mean   :2.367   Mean   :116427   Mean   :116338  
##  3rd Qu.:132086   3rd Qu.:2.555   3rd Qu.:169483   3rd Qu.:169181  
##  Max.   :457894   Max.   :2.910   Max.   :592971   Max.   :584880  
##                                                                    
##     SexRatio    
##  Min.   :0.900  
##  1st Qu.:0.970  
##  Median :1.000  
##  Mean   :1.007  
##  3rd Qu.:1.030  
##  Max.   :1.290  
## 
a <- 1
a
## [1] 1
class(a)
## [1] "numeric"
b <- c("30", "40", "50", "40", "30", "40", "20")
b
## [1] "30" "40" "50" "40" "30" "40" "20"
class(b)
## [1] "character"
factor(b)
## [1] 30 40 50 40 30 40 20
## Levels: 20 30 40 50
class(data)
## [1] "data.frame"
head(data$City)
## [1] 종로구    중구      용산구    성동구    광진구    동대문구 
## 240 Levels: 가평군  강남구  강동구  강릉시  강북구  강서구  ... 횡성군
data[1,]
##   X  Provinces    City Population Households PersInHou  Male Female
## 1 2 서울특별시 종로구      155695      72882      2.14 76962  78733
##   SexRatio
## 1     0.98
data[1,3]
## [1] 종로구 
## 240 Levels: 가평군  강남구  강동구  강릉시  강북구  강서구  ... 횡성군
head(data[c("Provinces", "City")],3)
##    Provinces    City
## 1 서울특별시 종로구 
## 2 서울특별시   중구 
## 3 서울특별시 용산구
data[data$Population > 1000000, c("Provinces", "City", "Population")]
##     Provinces    City Population
## 75     경기도 수원시     1177851
## 98     경기도 고양시     1015972
## 239  경상남도 창원시     1072222
data <- tbl_dt(data)
## Loading required namespace: data.table
#DATA FRAME - contains the data
#AESTHETIC MAPPINGS - how data are mapped to color, size, etc.
g <- ggplot(data, aes(Population, Households)) + theme_bw()
#GOEMS - points, lines, shapes
g + geom_point()

g + geom_point(aes(color=Provinces), size=4, alpha=.5)

#FACETS - the panels used in conditional plots
g + geom_point(aes(color=Provinces), size=4, alpha=.5) +
facet_grid(.~Provinces)

#STATS - binning, quantiles, and smoothing
g + geom_point(aes(color=Provinces), size=4, alpha=.5) + geom_smooth(method="lm")

#SCALES
g + geom_point(aes(color=Provinces), size=4, alpha=.5) + scale_y_log10()

# COORDINATE SYSTEM
g + geom_point(aes(color=Provinces), size=4, alpha=.5) + coord_polar(theta = "x", direction=1 ) 

ggplot(data, aes(x=factor(1), fill=factor(Provinces))) + geom_bar(width = 1) + coord_polar(theta = "y") + theme_bw() 

#THEME
g + geom_point(aes(color=Provinces), size=4, alpha=.5) + theme_bw()

g + geom_point(aes(color=Provinces), size=4, alpha=.5) + theme_minimal()

g + geom_point(aes(color=Provinces), size=4, alpha=.5) + theme_hc()

g + geom_point(aes(color=Provinces), size=4, alpha=.5) + theme_economist() 

# more sample
h <- ggplot(data, aes(PersInHou, SexRatio, fill=Provinces)) + theme_bw()
h + geom_point(aes(color=Provinces), size=4, alpha=.5)

h + geom_bar(stat="identity") #???

h + geom_point(aes(color=Provinces), size=4, alpha=.5) + facet_wrap(~Provinces) + geom_smooth(method="lm")
## Warning in qt((1 - level)/2, df): NaN이 생성되었습니다

filter(data, Provinces == "서울특별시")
## Source: local data table [25 x 9]
## 
##        X  Provinces      City Population Households PersInHou   Male
##    (int)     (fctr)    (fctr)      (int)      (int)     (dbl)  (int)
## 1      2 서울특별시   종로구      155695      72882      2.14  76962
## 2      3 서울특별시     중구      126817      59614      2.13  63292
## 3      4 서울특별시   용산구      235186     108138      2.17 114119
## 4      5 서울특별시   성동구      298145     126915      2.35 148265
## 5      6 서울특별시   광진구      362197     158769      2.28 177946
## 6      7 서울특별시 동대문구      362604     160110      2.26 181825
## 7      8 서울특별시   중랑구      417976     177077      2.36 208657
## 8      9 서울특별시   성북구      464176     192670      2.41 227676
## 9     10 서울특별시   강북구      333523     141325      2.36 164304
## 10    11 서울특별시   도봉구      353284     137260      2.57 174075
## ..   ...        ...       ...        ...        ...       ...    ...
##    Female
##     (int)
## 1   78733
## 2   63525
## 3  121067
## 4  149880
## 5  184251
## 6  180779
## 7  209319
## 8  236500
## 9  169219
## 10 179209
## ..    ...
## Variables not shown: SexRatio (dbl)
arrange(data, desc(Population))
## Source: local data table [263 x 9]
## 
##        X  Provinces    City Population Households PersInHou   Male Female
##    (int)     (fctr)  (fctr)      (int)      (int)     (dbl)  (int)  (int)
## 1     85     경기도 수원시     1177851     457894      2.57 592971 584880
## 2    256   경상남도 창원시     1072222     414432      2.59 544949 527273
## 3    108     경기도 고양시     1015972     387074      2.62 500004 515968
## 4     90     경기도 성남시      972466     389265      2.50 483718 488748
## 5    120     경기도 용인시      970062     351169      2.76 482584 487478
## 6     98     경기도 부천시      852220     327475      2.60 426251 425969
## 7    156   충청북도 청주시      832387     334276      2.49 417505 414882
## 8    105     경기도 안산시      703973     283031      2.49 360882 343091
## 9     25 서울특별시 송파구      664804     257528      2.58 324817 339987
## 10   190   전라북도 전주시      654138     253702      2.58 322350 331788
## ..   ...        ...     ...        ...        ...       ...    ...    ...
## Variables not shown: SexRatio (dbl)
select(data, Provinces, City, Households, PersInHou)
## Source: local data table [263 x 4]
## 
##     Provinces      City Households PersInHou
##        (fctr)    (fctr)      (int)     (dbl)
## 1  서울특별시   종로구       72882      2.14
## 2  서울특별시     중구       59614      2.13
## 3  서울특별시   용산구      108138      2.17
## 4  서울특별시   성동구      126915      2.35
## 5  서울특별시   광진구      158769      2.28
## 6  서울특별시 동대문구      160110      2.26
## 7  서울특별시   중랑구      177077      2.36
## 8  서울특별시   성북구      192670      2.41
## 9  서울특별시   강북구      141325      2.36
## 10 서울특별시   도봉구      137260      2.57
## ..        ...       ...        ...       ...
mutate(data, Population_mean = mean(Population))
## Source: local data table [263 x 10]
## 
##        X  Provinces      City Population Households PersInHou   Male
##    (int)     (fctr)    (fctr)      (int)      (int)     (dbl)  (int)
## 1      2 서울특별시   종로구      155695      72882      2.14  76962
## 2      3 서울특별시     중구      126817      59614      2.13  63292
## 3      4 서울특별시   용산구      235186     108138      2.17 114119
## 4      5 서울특별시   성동구      298145     126915      2.35 148265
## 5      6 서울특별시   광진구      362197     158769      2.28 177946
## 6      7 서울특별시 동대문구      362604     160110      2.26 181825
## 7      8 서울특별시   중랑구      417976     177077      2.36 208657
## 8      9 서울특별시   성북구      464176     192670      2.41 227676
## 9     10 서울특별시   강북구      333523     141325      2.36 164304
## 10    11 서울특별시   도봉구      353284     137260      2.57 174075
## ..   ...        ...       ...        ...        ...       ...    ...
##    Female
##     (int)
## 1   78733
## 2   63525
## 3  121067
## 4  149880
## 5  184251
## 6  180779
## 7  209319
## 8  236500
## 9  169219
## 10 179209
## ..    ...
## Variables not shown: SexRatio (dbl), Population_mean (dbl)
select(
        mutate(
                data, 
                Population_mean = mean(Population),
                Population_devi = round((Population_mean - Population),0)
                ),
        Provinces, City, Population, Population_mean, Population_devi
        )
## Source: local data table [263 x 5]
## 
##     Provinces      City Population Population_mean Population_devi
##        (fctr)    (fctr)      (int)           (dbl)           (dbl)
## 1  서울특별시   종로구      155695        232765.2           77070
## 2  서울특별시     중구      126817        232765.2          105948
## 3  서울특별시   용산구      235186        232765.2           -2421
## 4  서울특별시   성동구      298145        232765.2          -65380
## 5  서울특별시   광진구      362197        232765.2         -129432
## 6  서울특별시 동대문구      362604        232765.2         -129839
## 7  서울특별시   중랑구      417976        232765.2         -185211
## 8  서울특별시   성북구      464176        232765.2         -231411
## 9  서울특별시   강북구      333523        232765.2         -100758
## 10 서울특별시   도봉구      353284        232765.2         -120519
## ..        ...       ...        ...             ...             ...
summarise(data, Population_mean = mean(Population))
## Source: local data table [1 x 1]
## 
##   Population_mean
##             (dbl)
## 1        232765.2
by_prov <- group_by(data, Provinces)
popu <- summarise(by_prov, 
                  count = n(), 
                  pop_sum = sum(Population))
popu
## Source: local data table [16 x 3]
## 
##         Provinces count  pop_sum
##            (fctr) (int)    (int)
## 1      서울특별시    25 10078850
## 2      부산광역시    16  3517491
## 3      대구광역시     8  2491137
## 4      인천광역시    10  2914271
## 5      광주광역시     5  1476974
## 6      대전광역시     5  1525656
## 7      울산광역시     5  1169768
## 8          경기도    51 18723822
## 9          강원도    18  1547166
## 10       충청북도    15  2414568
## 11       충청남도    17  2671383
## 12       전라북도    16  2523806
## 13       전라남도    22  1902638
## 14       경상북도    25  3215695
## 15       경상남도    23  4428762
## 16 제주특별자치도     2   615250
ggplot(popu, aes(Provinces, count)) + geom_bar(stat="identity") + theme_pander() + scale_colour_pander()

#+theme_hc() + scale_colour_hc()

data %>% 
        select(prov = Provinces, city = City, pop = Population) %>%
        group_by(prov) %>%
        summarise(count = n(),
                  pop_sum = sum(pop)) %>%
        arrange(desc(pop_sum)) %>%
        print 
## Source: local data table [16 x 3]
## 
##              prov count  pop_sum
##            (fctr) (int)    (int)
## 1          경기도    51 18723822
## 2      서울특별시    25 10078850
## 3        경상남도    23  4428762
## 4      부산광역시    16  3517491
## 5        경상북도    25  3215695
## 6      인천광역시    10  2914271
## 7        충청남도    17  2671383
## 8        전라북도    16  2523806
## 9      대구광역시     8  2491137
## 10       충청북도    15  2414568
## 11       전라남도    22  1902638
## 12         강원도    18  1547166
## 13     대전광역시     5  1525656
## 14     광주광역시     5  1476974
## 15     울산광역시     5  1169768
## 16 제주특별자치도     2   615250
nomal <- data %>% 
        group_by(PersInHou) %>%
        summarise(count = n()) %>%
        mutate(prop = round(count/263, 2)) %>%
        print
## Source: local data table [87 x 3]
## 
##    PersInHou count  prop
##        (dbl) (int) (dbl)
## 1       2.14     8  0.03
## 2       2.13     3  0.01
## 3       2.17     6  0.02
## 4       2.35     1  0.00
## 5       2.28     2  0.01
## 6       2.26     3  0.01
## 7       2.36     5  0.02
## 8       2.41     2  0.01
## 9       2.57    12  0.05
## 10      2.63     4  0.02
## ..       ...   ...   ...
g <- ggplot(nomal, aes(PersInHou, count))
g + geom_bar(stat = "identity")

g <- ggplot(nomal, aes(PersInHou, prop))
g + geom_bar(stat = "identity")

2. 통계분석

목표 : 성비 데이터의 분포를 살펴보고, 이상치(Outlier)가 측정되는 city 리스트를 추출하자.

summary(data)
##        X              Provinces       City       Population     
##  Min.   :  2.0   경기도    :51   동구   :  6   Min.   :  10304  
##  1st Qu.: 72.5   경상북도  :25   중구   :  6   1st Qu.:  63302  
##  Median :143.0   서울특별시:25   남구   :  5   Median : 184992  
##  Mean   :142.3   경상남도  :23   서구   :  5   Mean   : 232765  
##  3rd Qu.:212.5   전라남도  :22   북구   :  4   3rd Qu.: 341550  
##  Max.   :281.0   강원도    :18   강서구 :  2   Max.   :1177851  
##                  (Other)   :99   (Other):235                    
##    Households       PersInHou          Male            Female      
##  Min.   :  5365   Min.   :1.860   Min.   :  5518   Min.   :  4786  
##  1st Qu.: 28785   1st Qu.:2.170   1st Qu.: 31671   1st Qu.: 32096  
##  Median : 74214   Median :2.370   Median : 93176   Median : 91925  
##  Mean   : 93816   Mean   :2.367   Mean   :116427   Mean   :116338  
##  3rd Qu.:132086   3rd Qu.:2.555   3rd Qu.:169483   3rd Qu.:169181  
##  Max.   :457894   Max.   :2.910   Max.   :592971   Max.   :584880  
##                                                                    
##     SexRatio    
##  Min.   :0.900  
##  1st Qu.:0.970  
##  Median :1.000  
##  Mean   :1.007  
##  3rd Qu.:1.030  
##  Max.   :1.290  
## 
g <- ggplot(data, aes(SexRatio)) + theme_bw()
g + geom_histogram(bins = 50, fill = "steelblue", position="identity") + 
        ggtitle("전국 지역별 성비 분포") +
        geom_vline(aes(xintercept=mean(SexRatio)), color="blue", linetype="dashed", size=1) +
        geom_vline(aes(xintercept=median(SexRatio)), color="red", linetype="dashed", size=1) 

data_sex <- data %>% select(Provinces, City, Male, Female, Population) %>%
        gather(sex, count, -Provinces, -City, -Population) %>%
        mutate(prop = count/Population) %>%
        print
## Source: local data table [526 x 6]
## 
##     Provinces      City Population   sex  count      prop
##        (fctr)    (fctr)      (int) (chr)  (int)     (dbl)
## 1  서울특별시   종로구      155695  Male  76962 0.4943126
## 2  서울특별시     중구      126817  Male  63292 0.4990814
## 3  서울특별시   용산구      235186  Male 114119 0.4852287
## 4  서울특별시   성동구      298145  Male 148265 0.4972916
## 5  서울특별시   광진구      362197  Male 177946 0.4912962
## 6  서울특별시 동대문구      362604  Male 181825 0.5014423
## 7  서울특별시   중랑구      417976  Male 208657 0.4992081
## 8  서울특별시   성북구      464176  Male 227676 0.4904950
## 9  서울특별시   강북구      333523  Male 164304 0.4926317
## 10 서울특별시   도봉구      353284  Male 174075 0.4927339
## ..        ...       ...        ...   ...    ...       ...
barplot(data_sex$count)

data %>% summarise(mean = mean(SexRatio),
                   median = median(SexRatio),
                   var = var(SexRatio),
                   sd = sd(SexRatio))
## Source: local data table [1 x 4]
## 
##       mean median         var         sd
##      (dbl)  (dbl)       (dbl)      (dbl)
## 1 1.006882      1 0.002675738 0.05172754
range(data$SexRatio)
## [1] 0.90 1.29
summary(data$SexRatio)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   0.900   0.970   1.000   1.007   1.030   1.290
quantile(data$SexRatio)
##   0%  25%  50%  75% 100% 
## 0.90 0.97 1.00 1.03 1.29
ggplot(data, aes(factor(1), SexRatio)) + geom_boxplot() + theme_bw() +
        ggtitle("전국 지역별 성비 분포")

distIQR <- IQR(data$SexRatio, na.rm=T)
posIQR <- quantile(data$SexRatio, probs=c(0.25, 0.75), na.rm=T)
downWhisker <- posIQR[[1]] - distIQR*1.5 ; upWhisker <- posIQR[[2]] + distIQR*1.5
downWhisker; upWhisker
## [1] 0.88
## [1] 1.12
outlier <- data %>%
        filter(SexRatio < downWhisker | SexRatio > upWhisker) %>%
        select(Provinces, City, Population, SexRatio) %>%
        arrange(desc(SexRatio)) %>%
        print
## Source: local data table [8 x 4]
## 
##    Provinces    City Population SexRatio
##       (fctr)  (fctr)      (int)    (dbl)
## 1 인천광역시 옹진군       20825     1.29
## 2     강원도 화천군       26790     1.27
## 3     강원도 인제군       33352     1.19
## 4     강원도 양구군       24283     1.17
## 5     강원도 고성군       30066     1.15
## 6   경상북도 울릉군       10304     1.15
## 7 울산광역시   동구      174903     1.13
## 8     강원도 철원군       49122     1.13