2장. R 기본 2단계
- 1단계에서 다루었던 내용에 대해서 복습을 합니다.
- 결측치처리 방법에 대해서 다룹니다.
- 이상치 관측 방법에 대해서 다룹니다.
- 문자열 데이터를 다루는 법에 대해서 다룹니다.
- 변수 간의 상관성 분석에 대해서 다룹니다.
데이터 다운로드 링크: https://www.kaggle.com/PromptCloudHQ/imdb-data
Ch1. IMDB_MOVIE_DATA_SET 데이터 불러오기
# 데이터 불러오기
DATA=read.csv("C:\\R/IMDB-Movie-Data.csv")
# 데이터 구조 파악
str(DATA)
## 'data.frame':    1000 obs. of  12 variables:
##  $ Rank              : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Title             : Factor w/ 999 levels "(500) Days of Summer",..: 288 569 656 636 674 780 403 471 834 538 ...
##  $ Genre             : Factor w/ 207 levels "Action","Action,Adventure",..: 12 86 196 93 8 8 117 109 3 75 ...
##  $ Description       : Factor w/ 1000 levels "\"21\" is the fact-based story about six MIT students who were trained to become experts in card counting and s"| __truncated__,..: 97 538 881 606 218 520 123 109 276 238 ...
##  $ Director          : Factor w/ 644 levels "Aamir Khan","Abdellatif Kechiche",..: 266 519 392 106 137 641 123 559 265 449 ...
##  $ Actors            : Factor w/ 996 levels "Aamir Khan, Anushka Sharma, Sanjay Dutt,Boman Irani",..: 185 737 419 659 972 650 810 314 154 456 ...
##  $ Year              : int  2014 2012 2016 2016 2016 2016 2016 2016 2016 2016 ...
##  $ Runtime..Minutes. : int  121 124 117 108 123 103 128 89 141 116 ...
##  $ Rating            : num  8.1 7 7.3 7.2 6.2 6.1 8.3 6.4 7.1 7 ...
##  $ Votes             : int  757074 485820 157606 60545 393727 56036 258682 2490 7188 192177 ...
##  $ Revenue..Millions.: num  333 126 138 270 325 ...
##  $ Metascore         : int  76 65 62 59 40 42 93 71 78 41 ...
head(DATA)
##   Rank                   Title                    Genre
## 1    1 Guardians of the Galaxy  Action,Adventure,Sci-Fi
## 2    2              Prometheus Adventure,Mystery,Sci-Fi
## 3    3                   Split          Horror,Thriller
## 4    4                    Sing  Animation,Comedy,Family
## 5    5           Suicide Squad Action,Adventure,Fantasy
## 6    6          The Great Wall Action,Adventure,Fantasy
##                                                                                                                                                                                                                      Description
## 1                                                                                                A group of intergalactic criminals are forced to work together to stop a fanatical warrior from taking control of the universe.
## 2                                                                                                Following clues to the origin of mankind, a team finds a structure on a distant moon, but they soon realize they are not alone.
## 3                                                                  Three girls are kidnapped by a man with a diagnosed 23 distinct personalities. They must try to escape before the apparent emergence of a frightful new 24th.
## 4 In a city of humanoid animals, a hustling theater impresario's attempt to save his theater with a singing competition becomes grander than he anticipates even as its finalists' find that their lives will never be the same.
## 5                                            A secret government agency recruits some of the most dangerous incarcerated super-villains to form a defensive task force. Their first mission: save the world from the apocalypse.
## 6                                                                             European mercenaries searching for black powder become embroiled in the defense of the Great Wall of China against a horde of monstrous creatures.
##               Director
## 1           James Gunn
## 2         Ridley Scott
## 3   M. Night Shyamalan
## 4 Christophe Lourdelet
## 5           David Ayer
## 6          Yimou Zhang
##                                                                       Actors
## 1                       Chris Pratt, Vin Diesel, Bradley Cooper, Zoe Saldana
## 2    Noomi Rapace, Logan Marshall-Green, Michael Fassbender, Charlize Theron
## 3           James McAvoy, Anya Taylor-Joy, Haley Lu Richardson, Jessica Sula
## 4 Matthew McConaughey,Reese Witherspoon, Seth MacFarlane, Scarlett Johansson
## 5                         Will Smith, Jared Leto, Margot Robbie, Viola Davis
## 6                              Matt Damon, Tian Jing, Willem Dafoe, Andy Lau
##   Year Runtime..Minutes. Rating  Votes Revenue..Millions. Metascore
## 1 2014               121    8.1 757074             333.13        76
## 2 2012               124    7.0 485820             126.46        65
## 3 2016               117    7.3 157606             138.12        62
## 4 2016               108    7.2  60545             270.32        59
## 5 2016               123    6.2 393727             325.02        40
## 6 2016               103    6.1  56036              45.13        42
- 변수 설명
- Rank
- Title : 영화 제목
- Genre : 영화 장르
- Description : 영화 설명
- Director : 감독명
- Actors : 배우
- Year : 영화 상영 년도
- Runtime..Minutes : 상영시간
- Rating : Rating 점수
- Votes : 관객 수
- Revenue..Millions : 수익
- Metascore : 메타 스코어
 
Ch2. 결측치 처리
결측치(Missing Value)는 말 그대로 데이터에 값이 없는 것을 뜻합니다. 줄여서 'NA'라고 표현하기도 하고, 다른 언어에서는 Null 이란 표현을 많이 씁니다. 결측치는 데이터를 분석하는데에 있어서 매우 방해가 되는 존재입니다. 결측치는 다음과 같은 문제를 야기합니다.
- 결측치를 다 제거할 경우, 막대한 데이터 손실을 불러일으킬 수 있습니다.
- 결측치를 잘못 대체할 경우, 데이터에서 편향(bias)이 생길 수가 있습니다.
- 결측치를 처리하는 데에 있어 분석가의 견해가 가장 많이 반영되며, 이 때문에 잘못될 경우 분석결과가 매우 틀어질 수도 있다.
- 결측치를 자세히 처리하기 위해서는 시간이 많이 투자되어야 합니다. 무엇보다, 데이터에 기반한 결측치 처리가 진행되어야 분석을 정확하게 진행할 수 있습니다.
# 결측치 확인
is.na(DATA$Metascore)[1:100] # Metascore 변수 내에서 결측치 논리문 판단 (True, False) , 1 ~ 100번째 값만 관찰
##   [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [23] FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
##  [34] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE
##  [45] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [56] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [67] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [78] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
##  [89] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [100] FALSE
sum(is.na(DATA$Metascore)) # Metascore 변수 내에 결측치 갯수
## [1] 64
colSums(is.na(DATA)) # DATA 내 모든 변수별 결측치 갯수
##               Rank              Title              Genre 
##                  0                  0                  0 
##        Description           Director             Actors 
##                  0                  0                  0 
##               Year  Runtime..Minutes.             Rating 
##                  0                  0                  0 
##              Votes Revenue..Millions.          Metascore 
##                  0                128                 64
# 결측치 전부 삭제
# 가장 극단적인 방법, 결측치가 하나라도 포함된 obs(행)은 삭제
DATA2 = na.omit(DATA) 
colSums(is.na(DATA2))
##               Rank              Title              Genre 
##                  0                  0                  0 
##        Description           Director             Actors 
##                  0                  0                  0 
##               Year  Runtime..Minutes.             Rating 
##                  0                  0                  0 
##              Votes Revenue..Millions.          Metascore 
##                  0                  0                  0
# 특정 변수에 결측치가 존재하는 행 삭제
# 12번째 변수에 해당되는 MetaScore가 결측치인 obs(행) 모두 제거
DATA3 = DATA[complete.cases(DATA[ ,12]),]
colSums(is.na(DATA3))
##               Rank              Title              Genre 
##                  0                  0                  0 
##        Description           Director             Actors 
##                  0                  0                  0 
##               Year  Runtime..Minutes.             Rating 
##                  0                  0                  0 
##              Votes Revenue..Millions.          Metascore 
##                  0                 98                  0
# 결측치 대체 
DATA$Metascore2=DATA$Metascore
DATA$Metascore2[is.na(DATA$Metascore2)]=58.99 # is.na가 True인 값들에 대해 58.99 지정
# 결측치 신경 안쓰고 계산하기
mean(DATA$Revenue..Millions.) # NA 생성
## [1] NA
mean(DATA$Revenue..Millions.,na.rm = TRUE) # NA 생략하고 계산
## [1] 82.95638
- 데이터를 다룰 때, 기본적으로 raw data는 절대 건드리는 것이 아닙니다. 
- 보통의 경우, 데이터를 새로 복사를 해두고 진행을 하는 것이 나중을 위해 매우 좋은 습관이 됩니다. 
- 결측치를 대체하는 방법은 다음과 같습니다. - 가장 기본적인 방법
- 연속형 변수 : 평균으로 대체
- 이산형 변수 : 최빈값으로 대체
 - 하지만 이렇게 무턱대고 결측치를 대체하는 경우에는 데이터가 심하게 쏠릴 수가 있습니다. 결측치를 대체할 때는 항상 다음의 사항들을 확인해야 됩니다. - 결측치의 비율
- 데이터의 분포
- 다른 변수와의 관계가 있는지
 - 데이터를 분석 할 때, 항상 데이터의 분포를 확인하고 진행을 해야됩니다. 데이터가 평균을 중심으로 균형있게 퍼져있는 '정규분포'형태를 뛰고 있는 경우는 모르지만, 현실의 대부분 데이터는 그렇게 이상적이지는 않기 때문입니다. 다음의 그래프를 보면서 확인해보겠습니다. 
summary(DATA$Revenue..Millions.)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    0.00   13.27   47.98   82.96  113.72  936.63     128
library(ggplot2)
ggplot(DATA,aes(x=Revenue..Millions.)) +
  geom_histogram(fill='royalblue') +
  ylab('') +
  xlab("Revenue_Millions")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 128 rows containing non-finite values (stat_bin).
- Revenu_Millions를 볼 때 데이터가 한쪽으로 매우 치우쳐져 있습니다.
- 이런 분포는 항상 평균과 중위수의 차이를 확인해봐야합니다. (평균: 82.96, 중위수: 47.98)
- 따리서, 이런 분포의 데이터의 결측치는 평균으로 대체하면 매우 위험합니다.
- 평균은 극단값(Outlier)에 영향을 받기 때문입니다. 극단값은 패턴을 벗어난 특수한 상황이지, 결코 일반적인 상황을 대변해주지 않습니다.
 
그럼 어떻게 해야하는가?
- 평균보다는 중위수가 안전합니다. 중위수는 극단값(Outlier)에 영향을 받지 않기 때문입니다.
- 그렇다고 해도, 중위수로 대체 하는 것은 차선책이지 완벽한 방법은 아닙니다.
- 다른 변수들과의 관계를 보면서 대체하는 것이 많은 시간을 요구하지만, 더 정교한 분석결과를 뽑아낼 수 있습니다.
- 다른 변수들을 정리해보고 더 자세한 결측치 대체방법을 다루도록 해보겠습니다.
 
