[R 프로그래밍] 14. Aggregating

Author : tmlab / Date : 2016. 10. 4. 01:22 / Category : Lecture/R 프로그래밍


PR14

Aggregating

1. 데이터 로딩

  • 데이터는 케이블 Tv이용 관련 고객세그먼트 데이터
  • 총 7개의 변수 (나이, 성별, 수입, 자녀수, 주거형태, 이용여부, 세그먼트)
In [98]:
seg.df <- read.csv("http://goo.gl/qw303p")
head(seg.df)
Out[98]:
agegenderincomekidsownHomesubscribeSegment
147.31613Male49482.812ownNosubNoSuburb mix
231.38684Male35546.291ownYessubNoSuburb mix
343.20034Male44169.190ownYessubNoSuburb mix
437.317Female81041.991ownNosubNoSuburb mix
540.95439Female79353.013ownYessubNoSuburb mix
643.03387Male58143.364ownYessubNoSuburb mix

1.1 데이터 탐색

  • 연령범위(19~80) / 성별은 남년반반 / 소득은 음수있음 / 자녀수(1~7) / 자가비율반반 / 이용자 40명 / 세그먼트 4가지
In [12]:
summary(seg.df)
Out[12]:
      age           gender        income            kids        ownHome   
 Min.   :19.26   Female:157   Min.   : -5183   Min.   :0.00   ownNo :159  
 1st Qu.:33.01   Male  :143   1st Qu.: 39656   1st Qu.:0.00   ownYes:141  
 Median :39.49                Median : 52014   Median :1.00               
 Mean   :41.20                Mean   : 50937   Mean   :1.27               
 3rd Qu.:47.90                3rd Qu.: 61403   3rd Qu.:2.00               
 Max.   :80.49                Max.   :114278   Max.   :7.00               
  subscribe         Segment   
 subNo :260   Moving up : 70  
 subYes: 40   Suburb mix:100  
              Travelers : 80  
              Urban hip : 50  
                              
                              
  • 수치형 3가지(정수,실수), 명목형4가지
In [13]:
str(seg.df)
'data.frame':	300 obs. of  7 variables:
 $ age      : num  47.3 31.4 43.2 37.3 41 ...
 $ gender   : Factor w/ 2 levels "Female","Male": 2 2 2 1 1 2 2 2 1 1 ...
 $ income   : num  49483 35546 44169 81042 79353 ...
 $ kids     : int  2 1 0 1 3 4 3 0 1 0 ...
 $ ownHome  : Factor w/ 2 levels "ownNo","ownYes": 1 2 2 1 2 2 1 1 1 2 ...
 $ subscribe: Factor w/ 2 levels "subNo","subYes": 1 1 1 1 1 1 1 1 1 1 ...
 $ Segment  : Factor w/ 4 levels "Moving up","Suburb mix",..: 2 2 2 2 2 2 2 2 2 2 ...

2. data aggregating

  • 특정조건에 따라 합산, 평균, 분산 등 합계정보를 계산
  • attach함수로 데이터에 접근이 편리하도록 함
  • mean, sd, by, aggregate, cut등의 함수를 활용
In [18]:
attach(seg.df)
The following objects are masked from seg.df (pos = 3):

    age, gender, income, kids, ownHome, Segment, subscribe

The following objects are masked from seg.df (pos = 4):

    age, gender, income, kids, ownHome, Segment, subscribe

The following objects are masked from seg.df (pos = 5):

    age, gender, income, kids, ownHome, Segment, subscribe

The following objects are masked from seg.df (pos = 6):

    age, gender, income, kids, ownHome, Segment, subscribe

The following objects are masked from seg.df (pos = 7):

    age, gender, income, kids, ownHome, Segment, subscribe

The following objects are masked from seg.df (pos = 8):

    age, gender, income, kids, ownHome, Segment, subscribe

2.1 mean, sd 등 다양한 통계함수

  • 대괄호 연산자(서브셋)를 활용해 특정 조건의 기술통계치를 산출
  • Moving up세그먼트 집단의 소득평균
In [16]:
attach(seg.df)
mean(income[Segment == "Moving up"])
Out[16]:
53090.9652534851
  • Moving up세그먼트인 동시에 서비스를 이용하고 있지 않은 집단의 소득평균
In [17]:
mean(income[Segment == "Moving up" & subscribe == "subNo"])
Out[17]:
53633.7334645083

2.2 apply

  • apply함수로 특정 조건에 해당하는 집단의 평균 산출할 수 있다.
  • apply(데이터, 행열기준, 함수)
In [29]:
apply(seg.df[,c(1,3,4)], MARGIN=2, FUN=mean)
Out[29]:
age
41.1996498660621
income
50936.5361836226
kids
1.27
In [30]:
apply(seg.df[Segment == 'Moving up', c(1,3,4)], MARGIN=2, FUN=mean)
Out[30]:
age
36.3311444509258
income
53090.9652534851
kids
1.91428571428571

2.3 table

  • 특정 조건에 해당한는 변수들의 조합에 따라 빈도를 파악할 수 있다.
In [35]:
table(ownHome,subscribe)
Out[35]:
        subscribe
ownHome  subNo subYes
  ownNo    137     22
  ownYes   123     18
In [54]:
table(kids)
Out[54]:
kids
  0   1   2   3   4   5   6   7 
121  70  51  36  13   6   2   1 
In [46]:
table(Segment,kids, subscribe)
Out[46]:
, , subscribe = subNo

            kids
Segment       0  1  2  3  4  5  6  7
  Moving up  12  9 15 11  5  3  0  1
  Suburb mix 11 35 20 17  7  3  1  0
  Travelers  70  0  0  0  0  0  0  0
  Urban hip  16 12  7  4  1  0  0  0

, , subscribe = subYes

            kids
Segment       0  1  2  3  4  5  6  7
  Moving up   1  8  3  2  0  0  0  0
  Suburb mix  0  1  2  2  0  0  1  0
  Travelers  10  0  0  0  0  0  0  0
  Urban hip   1  5  4  0  0  0  0  0

2.4 by

  • 특정 변수기준으로 기술 통계량 확인할수 있다.
  • by함수는 결과값을 리스트형태로 반환한다.
In [48]:
by(income, Segment, mean)
Out[48]:
Segment: Moving up
[1] 53090.97
------------------------------------------------------------ 
Segment: Suburb mix
[1] 55033.82
------------------------------------------------------------ 
Segment: Travelers
[1] 62213.94
------------------------------------------------------------ 
Segment: Urban hip
[1] 21681.93
In [49]:
by(income, list(Segment, subscribe), mean)
Out[49]:
: Moving up
: subNo
[1] 53633.73
------------------------------------------------------------ 
: Suburb mix
: subNo
[1] 54942.69
------------------------------------------------------------ 
: Travelers
: subNo
[1] 62746.11
------------------------------------------------------------ 
: Urban hip
: subNo
[1] 22082.11
------------------------------------------------------------ 
: Moving up
: subYes
[1] 50919.89
------------------------------------------------------------ 
: Suburb mix
: subYes
[1] 56461.41
------------------------------------------------------------ 
: Travelers
: subYes
[1] 58488.77
------------------------------------------------------------ 
: Urban hip
: subYes
[1] 20081.19

2.5 aggregate

  • aggregate 함수는 기준이 되는 변수가 리스트여야한다.
  • aggregate 함수는 결과값을 데이터프레임으로 출력해준다.
  • 포뮬러를 사용해 한번에 여러개 변인의 통계치를 산출할 수 있다.
In [50]:
aggregate(income, list(Segment), mean)
Out[50]:
Group.1x
1Moving up53090.97
2Suburb mix55033.82
3Travelers62213.94
4Urban hip21681.93
In [51]:
aggregate(income ~ Segment, data=seg.df, mean)
Out[51]:
Segmentincome
1Moving up53090.97
2Suburb mix55033.82
3Travelers62213.94
4Urban hip21681.93
In [52]:
aggregate(income ~ Segment + ownHome, data = seg.df, mean)
Out[52]:
SegmentownHomeincome
1Moving upownNo54497.68
2Suburb mixownNo54932.83
3TravelersownNo63188.42
4Urban hipownNo21337.59
5Moving upownYes50216.37
6Suburb mixownYes55143.21
7TravelersownYes61889.12
8Urban hipownYes23059.27
In [53]:
aggregate(income ~ Segment + ownHome + subscribe, data = seg.df, mean)
Out[53]:
SegmentownHomesubscribeincome
1Moving upownNosubNo55402.89
2Suburb mixownNosubNo54579.99
3TravelersownNosubNo65852.54
4Urban hipownNosubNo21604.16
5Moving upownYessubNo49898.85
6Suburb mixownYessubNo55354.86
7TravelersownYessubNo61749.71
8Urban hipownYessubNo23993.93
9Moving upownNosubYes50675.7
10Suburb mixownNosubYes63753.97
11TravelersownNosubYes48091.75
12Urban hipownNosubYes20271.33
13Moving upownYessubYes51359.44
14Suburb mixownYessubYes52815.13
15TravelersownYessubYes62944.64
16Urban hipownYessubYes19320.64

3. 데이터의 변환

3.1 cut함수 (데이터변환 : 연속형변수를 다항변수로)

  • 연속형 변수를 구간으로 나누어 명목형 변수로 변환해주는 함수
  • cut(데이터, breaks=구간수, labels = 구간이름)
In [62]:
cut.data = aggregate(income ~ Segment + ownHome + subscribe, data = seg.df, mean)

cut.data$income2 = cut(agr.data$income, 
                       breaks = c(0,20000,30000,40000,50000,60000,70000), 
                       labels = c('2만이하', '2만~3만', '3만~4만', '4만~5만','5만~6만', '6만이상'))
In [63]:
cut.data
Out[63]:
SegmentownHomesubscribeincomeincome2
1Moving upownNosubNo55402.895만~6만
2Suburb mixownNosubNo54579.995만~6만
3TravelersownNosubNo65852.546만이상
4Urban hipownNosubNo21604.162만~3만
5Moving upownYessubNo49898.854만~5만
6Suburb mixownYessubNo55354.865만~6만
7TravelersownYessubNo61749.716만이상
8Urban hipownYessubNo23993.932만~3만
9Moving upownNosubYes50675.75만~6만
10Suburb mixownNosubYes63753.976만이상
11TravelersownNosubYes48091.754만~5만
12Urban hipownNosubYes20271.332만~3만
13Moving upownYessubYes51359.445만~6만
14Suburb mixownYessubYes52815.135만~6만
15TravelersownYessubYes62944.646만이상
16Urban hipownYessubYes19320.642만이하

3.2 grep 함수 (Pattern Matching)

  • 데이터 내에서 특정 패턴을 찾는데 사용한다.
  • 데이터의 위치값, 데이터값 자체를 찾을 수 있다.
  • grepl 특정패턴이 존재하는지에 대한 논리값을 반환한다.
  • 공통된 패턴을 가진 자료들의 위치를 찾아서 위치값을 활용해 데이터를 변환할때 사용한다.
In [73]:
grep("ap", c("apple", "Apple", "apple2", "bbapple")) #ap를 포함하는 원소들의 위치
Out[73]:
  1. 1
  2.  
  3. 3
  4.  
  5. 4
In [71]:
grepl("ap", c("apple", "Apple", "apple2", "bbapple")) #ap를 포함하는 원소들의 위치
Out[71]:
  1. TRUE
  2.  
  3. FALSE
  4.  
  5. TRUE
  6.  
  7. TRUE
In [72]:
grep("ap", c("apple", "Apple", "apple2", "bbapple"), value=TRUE) #ap를 포함하는 원소
Out[72]:
  1. 'apple'
  2.  
  3. 'apple2'
  4.  
  5. 'bbapple'
In [88]:
grep("[1-3]", c("apple1", "apple2", "apple3", "apple4", "Apple1")) #1,2,3을 포함하는 원소위치
Out[88]:
  1. 1
  2.  
  3. 2
  4.  
  5. 3
  6.  
  7. 5
In [82]:
seg.df$ownHome = as.character(seg.df$ownHome)
In [80]:
grep('Yes', seg.df$ownHome)
Out[80]:
  1. 2
  2.  
  3. 3
  4.  
  5. 5
  6.  
  7. 6
  8.  
  9. 10
  10.  
  11. 11
  12.  
  13. 14
  14.  
  15. 15
  16.  
  17. 16
  18.  
  19. 17
  20.  
  21. 18
  22.  
  23. 19
  24.  
  25. 20
  26.  
  27. 21
  28.  
  29. 22
  30.  
  31. 24
  32.  
  33. 25
  34.  
  35. 26
  36.  
  37. 33
  38.  
  39. 37
  40.  
  41. 39
  42.  
  43. 40
  44.  
  45. 41
  46.  
  47. 43
  48.  
  49. 47
  50.  
  51. 50
  52.  
  53. 51
  54.  
  55. 52
  56.  
  57. 53
  58.  
  59. 55
  60.  
  61. 57
  62.  
  63. 68
  64. 72
  65.  
  66. 73
  67.  
  68. 75
  69.  
  70. 79
  71.  
  72. 80
  73.  
  74. 81
  75.  
  76. 83
  77.  
  78. 84
  79.  
  80. 87
  81.  
  82. 90
  83.  
  84. 91
  85.  
  86. 92
  87.  
  88. 95
  89.  
  90. 96
  91.  
  92. 97
  93.  
  94. 99
  95.  
  96. 108
  97.  
  98. 118
  99.  
  100. 120
  101.  
  102. 122
  103.  
  104. 125
  105.  
  106. 130
  107.  
  108. 139
  109.  
  110. 144
  111.  
  112. 145
  113.  
  114. 150
  115.  
  116. 151
  117. 152
  118.  
  119. 153
  120.  
  121. 155
  122.  
  123. 156
  124.  
  125. 157
  126.  
  127. 159
  128.  
  129. 160
  130.  
  131. 161
  132.  
  133. 162
  134.  
  135. 163
  136.  
  137. 164
  138.  
  139. 165
  140.  
  141. 166
  142.  
  143. 167
  144.  
  145. 168
  146.  
  147. 169
  148.  
  149. 170
  150.  
  151. 171
  152.  
  153. 175
  154.  
  155. 176
  156.  
  157. 177
  158.  
  159. 178
  160.  
  161. 179
  162.  
  163. 180
  164. 181
  165.  
  166. 182
  167.  
  168. 183
  169.  
  170. 184
  171.  
  172. 185
  173.  
  174. 187
  175.  
  176. 188
  177.  
  178. 189
  179.  
  180. 190
  181.  
  182. 192
  183.  
  184. 194
  185.  
  186. 195
  187.  
  188. 196
  189.  
  190. 197
  191.  
  192. 198
  193.  
  194. 199
  195.  
  196. 200
  197.  
  198. 201
  199.  
  200. 203
  201.  
  202. 204
  203.  
  204. 207
  205.  
  206. 208
  207.  
  208. 210
  209.  
  210. 211
  211. 213
  212.  
  213. 214
  214.  
  215. 215
  216.  
  217. 216
  218.  
  219. 220
  220.  
  221. 221
  222.  
  223. 223
  224.  
  225. 224
  226.  
  227. 225
  228.  
  229. 226
  230.  
  231. 228
  232.  
  233. 231
  234.  
  235. 232
  236.  
  237. 236
  238.  
  239. 238
  240.  
  241. 240
  242.  
  243. 241
  244.  
  245. 247
  246.  
  247. 252
  248.  
  249. 258
  250.  
  251. 261
  252.  
  253. 264
  254.  
  255. 265
  256.  
  257. 269
  258. 271
  259.  
  260. 273
  261.  
  262. 274
  263.  
  264. 276
  265.  
  266. 279
  267.  
  268. 286
  269.  
  270. 293
  271.  
  272. 295
  273.  
  274. 296
  275.  
  276. 300

3.3 gsub함수 (Pattern Matching and Replacement)

  • Gsub함수는 데이터에 포함된 특정 패턴을 찾아서 수정한다.
  • Gsub(“찾는 패턴“, “수정할 패턴”, 데이터) 형식으로 사용한다.
In [100]:
seg.df$Segment = gsub(" ", "", seg.df$Segment)
In [102]:
head(seg.df)
Out[102]:
agegenderincomekidsownHomesubscribeSegment
147.31613Male49482.812ownNosubNoSuburbmix
231.38684Male35546.291ownYessubNoSuburbmix
343.20034Male44169.190ownYessubNoSuburbmix
437.317Female81041.991ownNosubNoSuburbmix
540.95439Female79353.013ownYessubNoSuburbmix
643.03387Male58143.364ownYessubNoSuburbmix


Archives

05-16 12:51

Contact Us

Address
경기도 수원시 영통구 원천동 산5번지 아주대학교 다산관 429호

E-mail
textminings@gmail.com

Phone
031-219-2910

Tags

Calendar

«   2024/05   »
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
Copyright © All Rights Reserved
Designed by CMSFactory.NET