-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
2185 lines (1885 loc) · 59.2 KB
/
index.html
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>R 语言中级培训</title>
<meta charset="utf-8">
<meta name="description" content="R 语言中级培训">
<meta name="author" content="Copyright @Transwarp Inc. | All Rights Reserved">
<meta name="generator" content="slidify" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link rel="stylesheet" href="./libraries/frameworks/io2012/css/default.css" media="all" >
<link rel="stylesheet" href="./libraries/frameworks/io2012/css/phone.css"
media="only screen and (max-device-width: 480px)" >
<link rel="stylesheet" href="./libraries/frameworks/io2012/css/slidify.css" >
<link rel="stylesheet" href="./libraries/highlighters/highlight.js/css/zenburn.css" />
<base target="_blank"> <!-- This amazingness opens all links in a new tab. -->
<!-- Grab CDN jQuery, fall back to local if offline -->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"></script>
<script>window.jQuery || document.write('<script src="./libraries/widgets/quiz/js/jquery.js"><\/script>')</script>
<script data-main="./libraries/frameworks/io2012/js/slides"
src="./libraries/frameworks/io2012/js/require-1.0.8.min.js">
</script>
</head>
<body style="opacity: 0">
<slides class="layout-widescreen">
<!-- LOGO SLIDE -->
<slide class="title-slide segue nobackground">
<hgroup class="auto-fadein">
<h1>R 语言中级培训</h1>
<h2>星环数据挖掘组_daitao.xing</h2>
<p>Copyright @Transwarp Inc. | All Rights Reserved<br/></p>
</hgroup>
<article></article>
</slide>
<!-- SLIDES -->
<slide class="" id="slide-1" style="background:;">
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-2" style="background:;">
<hgroup>
<h2>目录</h2>
</hgroup>
<article data-timings="">
<ul>
<li>R的核心</li>
<li>替代For的Apply家族函数</li>
<li>管道操作</li>
<li>数据获取</li>
<li>R高效数据处理</li>
<li>其他有关数据科学的topic </li>
<li>深入了解数据:ggplot2</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-3" style="background:;">
<hgroup>
<h2>R的核心:函数式编程思想</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-4" style="background:;">
<hgroup>
<h2>FP</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">1+2
</code></pre>
<pre><code>## [1] 3
</code></pre>
<pre><code class="r">'+'(1,2)
</code></pre>
<pre><code>## [1] 3
</code></pre>
<pre><code class="r">funs <- c(lm, median, sd, mad, IQR)
</code></pre>
<ul>
<li>Anonymous functions </li>
<li>Closures</li>
<li>List of functions</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-5" style="background:;">
<article data-timings="">
<pre><code class="r">summary <- function(x) {
c(mean(x, na.rm = TRUE),
median(x, na.rm = TRUE),
sd(x, na.rm = TRUE),
mad(x, na.rm = TRUE),
IQR(x, na.rm = TRUE))
}
summary <- function(x) {
funs <- c(mean, median, sd, mad, IQR)
lapply(funs, function(f) f(x, na.rm = TRUE))
}
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-6" style="background:;">
<hgroup>
<h2>闭包</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">power <- function(exponent) {
function(x) {
x ^ exponent
}
}
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-7" style="background:;">
<hgroup>
<h2>Lists of functions</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">compute_mean <- list(
base = function(x) mean(x),
sum = function(x) sum(x) / length(x),
manual = function(x) {
total <- 0
n <- length(x)
for (i in seq_along(x)) {
total <- total + x[i] / n
}
total
}
)
compute_mean$sum()
compute_mean[["sum"]]()
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-8" style="background:;">
<hgroup>
<h2>FP的效率</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">x <- c()
system.time({
for(i in 1:100000){
if(i %% 2 ==0)
x <- c(x,i)
}
})
</code></pre>
<pre><code>## user system elapsed
## 4.475 0.608 5.089
</code></pre>
<pre><code class="r">system.time({
x <- 1:100000
x[x %% 2 == 0]
})
</code></pre>
<pre><code>## user system elapsed
## 0.002 0.001 0.003
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-9" style="background:;">
<hgroup>
<h2>R中的管道操作</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-10" style="background:;">
<hgroup>
<h2>管道操作</h2>
</hgroup>
<article data-timings="">
<ul>
<li>shell |</li>
<li>magrittr 和 pipeR(renkun)</li>
<li>上一步输出为下一步的输入</li>
<li>比管道更加灵活(主动判断应该填入的位置)</li>
<li>%>% 将结果输送到函数的第一个参数</li>
<li>%>>% 将结果输送到表达式中.的位置</li>
<li>recharts</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-11" style="background:;">
<hgroup>
<h2>自定义的管道</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">`%^_^%` <- function(from,to) {
cat(paste(from,"smiles to",to))
}
"Ken" %^_^% "Jenny"
</code></pre>
<pre><code>## Ken smiles to Jenny
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-12" style="background:;">
<article data-timings="">
<pre><code class="r">library(magrittr)
rnorm(10000,mean=10,sd=1) %>>%
sample(.,size=length(.)*0.1,replace=FALSE) %>%
log %>%
diff %>>%
plot(.,col="red",type="l",
main=sprintf("length: %d",length(.)))
</code></pre>
<p><img src="assets/fig/unnamed-chunk-8-1.png" alt="plot of chunk unnamed-chunk-8"> </p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-13" style="background:;">
<hgroup>
<h2>R apply家族</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-14" style="background:;">
<hgroup>
<h2>替代for的高效函数</h2>
</hgroup>
<article data-timings="">
<ul>
<li>apply</li>
<li>mapply</li>
<li>lapply</li>
<li>sapply</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-15" style="background:;">
<hgroup>
<h2>apply(X,margin,FUN)</h2>
</hgroup>
<article data-timings="">
<p>对对象的每一个部分施加函数</p>
<pre><code class="r">apply(iris[,1:3],2,max)
</code></pre>
<pre><code>## Sepal.Length Sepal.Width Petal.Length
## 7.9 4.4 6.9
</code></pre>
<p>也可以对高维数组操作</p>
<pre><code class="r">x <- 1:27
dim(x) <- c(3,3,3)
apply(x, c(1,2), FUN = paste,collapse =",")
</code></pre>
<pre><code>## [,1] [,2] [,3]
## [1,] "1,10,19" "4,13,22" "7,16,25"
## [2,] "2,11,20" "5,14,23" "8,17,26"
## [3,] "3,12,21" "6,15,24" "9,18,27"
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-16" style="background:;">
<hgroup>
<h2>lapply(X,FUN)和sapply(X,FUN)</h2>
</hgroup>
<article data-timings="">
<p>对对象的每一个元素进行操作(当对象是DF时,逐列进行)</p>
<pre><code class="r">temp <- iris[,1:3]
head(sapply(temp,as.character))
</code></pre>
<pre><code>## Sepal.Length Sepal.Width Petal.Length
## [1,] "5.1" "3.5" "1.4"
## [2,] "4.9" "3" "1.4"
## [3,] "4.7" "3.2" "1.3"
## [4,] "4.6" "3.1" "1.5"
## [5,] "5" "3.6" "1.4"
## [6,] "5.4" "3.9" "1.7"
</code></pre>
<p>借助高效的管道函数,我们可以构造出更灵活的用法</p>
<pre><code class="r">sapply(1:3, . %>% seq_len %>% sum)
</code></pre>
<pre><code>## [1] 1 3 6
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-17" style="background:;">
<article data-timings="">
<pre><code class="r">funs2 <- list(
sum = function(x, ...) sum(x, ..., na.rm = TRUE),
mean = function(x, ...) mean(x, ..., na.rm = TRUE),
median = function(x, ...) median(x, ..., na.rm = TRUE)
)
lapply(funs2, function(f) f(x))
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-18" style="background:;">
<hgroup>
<h2>Mapply(FUN,....,MoreArg = ,....)</h2>
</hgroup>
<article data-timings="">
<ul>
<li>对多个对象逐个元素进行操作(比如对DF中的多列同时操作)</li>
</ul>
<pre><code class="r">mapply(paste,
1:5,letters[1:5],LETTERS[1:5],
MoreArgs = list(sep='-'))
</code></pre>
<pre><code>## [1] "1-a-A" "2-b-B" "3-c-C" "4-d-D" "5-e-E"
</code></pre>
<ul>
<li>当函数FUN需要多个参数输入时</li>
</ul>
<pre><code class="r">test <- c("0","01","002")
res <- mapply(function(x, y) paste0(rep(x, y), collapse = ""), 0, 3- nchar(test))
paste0(res,test)
</code></pre>
<pre><code>## [1] "000" "001" "002"
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-19" style="background:;">
<hgroup>
<h2>rollapply</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">library(zoo)
</code></pre>
<pre><code>##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
</code></pre>
<pre><code class="r">z <- rnorm(6)
rollapply(z, 2, sum)
</code></pre>
<pre><code>## [1] 0.8225873 2.0785559 -0.6813391 -1.9719372 -0.4199782
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-20" style="background:;">
<hgroup>
<h2>案例1:bootstrap 抽样</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">boot_lm <- function(formula,data,...){
function(){
lm(formula = formula,
data = data[sample(nrow(data),replace = T),],...)
}
}
iris_boot <- boot_lm(Sepal.Length ~ Petal.Length,iris)
bstrap <- sapply(X= 1:1000,
FUN = function(x) iris_boot()$coef)
apply(bstrap,MARGIN = 1,FUN = quantile,prob =c(0.025,0.5,0.975))
</code></pre>
<pre><code>## (Intercept) Petal.Length
## 2.5% 4.163022 0.3718770
## 50% 4.305461 0.4095615
## 97.5% 4.446607 0.4439611
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-21" style="background:;">
<hgroup>
<h2>案例2:担保链分析中的递归</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">findCon = function(uid,friends.connected,friends.whole){
tmp=c()
for(i in friends.connected){
for(j in 1:length(i)){
tmp1 = unique(rbind(friends.whole[friends.whole$to == i[j],],friends.whole[friends.whole$from == i[j],]))
tmp = unique(rbind(tmp,tmp1))
}
}
if(dim(unique(rbind(tmp,friends.connected)))[1] == dim(friends.connected)[1]){
return(friends.connected)
}else {
friends.connected=unique(rbind(tmp,friends.connected))
findCon(uid, friends.connected,friends.whole)
}
}
uid="20111214000138"
system.time({
friends.connected = unique(rbind(friends.whole[friends.whole$to ==uid,],friends.whole[friends.whole$from == uid,]))
friends.1=findCon(uid,friends.connected,friends.whole)
friends.1=friends.1[complete.cases(friends.1),]
})
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-22" style="background:;">
<article data-timings="">
<pre><code class="r">friends.whole<-read.table("data.csv",header=T,sep=",",col.names=c("from","to"))
findCon1 = function(friends.connected,friends.whole){
index <- 1:nrow(friends.whole)
len1 <- nrow(as.data.frame(friends.connected))
index_target <- unique(unlist(as.list((friends.connected))))
tmp <- sapply(friends.whole,function(x,y) y[x %in% index_target],index) %>%
unlist() %>%
unique()
friends.connected <- friends.whole[tmp,]
if(nrow(friends.connected) == len1){
return(friends.connected)
}else {
findCon1(friends.connected,friends.whole)
}
}
uid="20111214000138"
system.time({friends.1=findCon1(uid,friends.whole) %>%
unique()
})
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-23" style="background:;">
<article data-timings="">
<p><img src="./assets/fig/xiaoguo.png" alt="效果对比"></p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-24" style="background:;">
<hgroup>
<h2>R的数据获取,web scraping</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-25" style="background:;">
<article data-timings="">
<ul>
<li>XML package 结构化网页数据抓取</li>
<li>rvest package(Hadley god) (非结构化网页数据抓取)</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-26" style="background:;">
<hgroup>
<h2>结构化网页数据抓取:XML package</h2>
</hgroup>
<article data-timings="">
<pre><code class="r">library(XML)
url <- 'http://www.basketball-reference.com/teams/NYK/2015_games.html'
tables <- readHTMLTable(url,
stringsAsFactors = FALSE,
header=F)
data <- tables[[1]]
head(data,2)
</code></pre>
<pre><code>## V1 V2 V3 V4 V5 V6 V7 V8 V9
## 1 1 Wed, Oct 29, 2014 8:00p EST Box Score Chicago Bulls L
## 2 2 Thu, Oct 30, 2014 8:00p EST Box Score @ Cleveland Cavaliers W
## V10 V11 V12 V13 V14 V15
## 1 80 104 0 1 L 1
## 2 95 90 1 1 W 1
</code></pre>
<p>查看网页上的超链接</p>
<pre><code class="r">getHTMLLinks(url)
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-27" style="background:;">
<hgroup>
<h2>非结构化数据的获取:rvest package</h2>
</hgroup>
<article data-timings="">
<p><a href="http://www.w3schools.com/cssref/css_selectors.asp">css协议</a></p>
<pre><code class="r">library(rvest)
freak <- html_session("http://torrentfreak.com/top-10-most-pirated-movies-of-the-week-130304/")
freak %>%
html_nodes(".widg-topcomments-post-title") %>%
html_text() %>% .[1:2]
</code></pre>
<pre><code>## [1] "Transmission Releases Long-Awaited BitTorrent Client For Windows"
## [2] "Pirated ‘Star Wars: The Force Awakens’ Blu-Ray Leaks Online"
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-28" style="background:;">
<hgroup>
<h2>特征工程和数据预处理</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-29" style="background:;">
<hgroup>
<h2>reshape2</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-30" style="background:;">
<hgroup>
<h2>数据的两种形状</h2>
</hgroup>
<article data-timings="">
<p>统计中待分析的数据框通常有两种形式</p>
<ul>
<li>长型数据(堆叠数据),长型数据是各变量取值在一列中,而对应的变量名在另一列。</li>
<li>宽型数据(非堆叠数据),宽型数据一般是各变量取值类型一致,而变量以不同列的形式构成。</li>
</ul>
<p>例如iris的前四列子集即是一个典型的宽型数据。例如下面将宽型数据转为长型数据:</p>
<pre><code class="r">data_w <- iris[,1:4]
data_l <- stack(data_w)
data_w <- unstack(data_l)
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-31" style="background:;">
<hgroup>
<h2>数据的两种形状</h2>
</hgroup>
<article data-timings="">
<p>只要在一列中存在分类变量,都可以将其看作是长型数据。在上例中iris的前四列可以看作是宽型数据,但最后两列可以看作是一个长型数据。可以根据Species变量将数据转为宽型。并得到各花种类的平均值。</p>
<pre><code class="r">subdata <- iris[,4:5]
data_w <- unstack(subdata)
colMeans(data_w)
</code></pre>
<pre><code>## setosa versicolor virginica
## 0.246 1.326 2.026
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-32" style="background:;">
<hgroup>
<h2>数据重塑计算</h2>
</hgroup>
<article data-timings="">
<p>在实践中这种单纯的长宽格式互转并不多见,因为我们并不是需要不同的数据格式,而需要不同格式下的分析结果。在上例中我们先转换数据格式再计算分析结果,而更常见的是一步直接得到分析结果。此时我们需要的是更为强大的reshape2包。</p>
<pre><code class="r">library(reshape2)
dcast(data=subdata, # 分析对象
formula=Species~., # 数据分组的方式
value.var='Petal.Width', # 要计算的数值对象
fun=mean) # 计算用函数名
</code></pre>
<pre><code>## Species .
## 1 setosa 0.246
## 2 versicolor 1.326
## 3 virginica 2.026
</code></pre>
<p>dcast的思路和aggregate很相似,都是根据变量切分数据,再对分组后的数据进行计算,但dcast的输出格式和功能在多维情况下要方便很多。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-33" style="background:;">
<hgroup>
<h2>数据重塑计算</h2>
</hgroup>
<article data-timings="">
<p>即melt函数,将一个宽型数据融合成一个长型数据。例如我们将iris数据集进行融合。</p>
<pre><code class="r">iris_long <- melt(data=iris, # 要融合的对象
id='Species') # 哪些变量不参与到融合中
</code></pre>
<p>一个纯粹的长型数据,只包含一个数值变量,其它均为分类变量。而一个纯粹的宽型数据,则不包含分类变量,均为数值变量。而现实中你遇到要处理的数据,则多半是二者的混杂,正如iris数据集那样。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-34" style="background:;">
<hgroup>
<h2>数据重塑计算</h2>
</hgroup>
<article data-timings="">
<p>melt和dcast正如同是铁匠的两种得力工具,melt可以看作是炼炉,负责融合数据,成为一个纯粹的长型。而dcast则可以看作是铁锤,负责重铸数据,使之成为需要的格式,同时加以分析。下面的例子就是将之前生成的数据进行汇总计算</p>
<pre><code class="r">dcast(data=iris_long,
formula=Species~variable,
value.var='value',fun=mean)
</code></pre>
<pre><code>## Species Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1 setosa 5.006 3.428 1.462 0.246
## 2 versicolor 5.936 2.770 4.260 1.326
## 3 virginica 6.588 2.974 5.552 2.026
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-35" style="background:;">
<hgroup>
<h2>小练习</h2>
</hgroup>
<article data-timings="">
<p>tips数据集练习,它是一个餐厅侍者收集的关于小费的数据,其中包含了七个变量,包括总费用、付小费的金额、付款者性别、是否吸烟、日期、日间、顾客人数。计算不同性别顾客是否会支付不同的小费比例。则可以按sex变量汇集数据。</p>
<pre><code class="r">dcast(tips,sex~.,value.var='tip',fun=mean)
</code></pre>
<pre><code>## sex .
## 1 Female 2.833448
## 2 Male 3.089618
</code></pre>
<p>又或者,按sex和size变量划分数据,分别计算小费金额,可以观察到用餐人数越多时,小费相应给的越多,而且男性顾客一般会比女性顾客大方一点。</p>
<pre><code class="r">dcast(tips,sex~size,value.var='tip',fun=mean)
</code></pre>
<pre><code>## sex 1 2 3 4 5 6
## 1 Female 1.276667 2.528448 3.250000 4.021111 5.14 4.60
## 2 Male 1.920000 2.614184 3.476667 4.172143 3.75 5.85
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-36" style="background:;">
<hgroup>
<h2>dcast函数的使用前提</h2>
</hgroup>
<article data-timings="">
<ul>
<li>数据中已经存在分类变量,例如sex或者smoke</li>
<li>根据分类变量划分数据</li>
<li>再计算某个数值变量的指标</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-37" style="background:;">
<hgroup>
<h2>更复杂的需求</h2>
</hgroup>
<article data-timings="">
<p>如果我们想同时计算出不同性别顾客的小费和总费用。但现有的数据集中并没有这种分类变量,怎么处理呢?</p>
<p>一种是笨一点的方法,将前面用过的方法用两次,然后合并这两个结果。但这种方法在多变量情况下并不好。</p>
<pre><code class="r">dcast(tips,sex~.,value.var='tip',fun=mean)
</code></pre>
<pre><code>## sex .
## 1 Female 2.833448
## 2 Male 3.089618
</code></pre>
<pre><code class="r">dcast(tips,sex~.,value.var='total_bill',fun=mean)
</code></pre>
<pre><code>## sex .
## 1 Female 18.05690
## 2 Male 20.74408
</code></pre>
<p>另一种推荐的方法就是使用前面提到的melt函数,先将数据融合成纯粹的长型数据,再用dcast重铸。</p>
<pre><code class="r">tips_melt <- melt(data = tips, id.vars=c('sex','smoker','time','size','day'))
dcast(data = tips_melt, sex ~ variable, value.var='value',fun= mean)
</code></pre>
<pre><code>## sex total_bill tip
## 1 Female 18.05690 2.833448
## 2 Male 20.74408 3.089618
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-38" style="background:;">
<hgroup>
<h2>更复杂的需求</h2>
</hgroup>
<article data-timings="">
<p>要同时考虑不同性别和吸烟习惯的顾客给小费的相对例。</p>
<pre><code class="r">tips_mean <- dcast(data = tips_melt, sex+ smoker~ variable, fun= mean)
tips_mean$rate <- with(tips_mean,tip/total_bill)
tips_mean
</code></pre>
<pre><code>## sex smoker total_bill tip rate
## 1 Female No 18.10519 2.773519 0.1531892
## 2 Female Yes 17.97788 2.931515 0.1630623
## 3 Male No 19.79124 3.113402 0.1573122
## 4 Male Yes 22.28450 3.051167 0.1369188
</code></pre>
<p>在dcast函数中的公式同时考虑到了三个分类变量,在第二步计算了小费相对于总餐费的比率,可以清楚的看到,吸烟的女性顾客相对是最大方的,而吸烟的男性则是最小气的。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-39" style="background:;">
<hgroup>
<h2>时间相关数据的类别</h2>
</hgroup>
<article data-timings="">
<ul>
<li>时间类对象,仅包含日期和时间信息的数据</li>
<li>时间序列类对象,在一个普通的数据对象上附加了时间戳的数据</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-40" style="background:;">
<hgroup>
<h2>时间类对象</h2>
</hgroup>
<article data-timings="">
<ul>
<li>简单的Date类型,只包含日期而不包含时钟信息</li>
<li>复杂的POSIXct类型。不仅包括日期还包括了时钟和时区信息。</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-41" style="background:;">
<hgroup>
<h2>Date类型</h2>
</hgroup>
<article data-timings="">
<p>数据量少的情况下,可以手工输入为字符串格式,然后转为Date类型,数据量多的话应从外部文件输入,再转为Date格式,两种方式都需要as.Date函数。</p>
<pre><code class="r">date1 <- '1989-05-04'
date1 <- as.Date(date1)
class(date1)
</code></pre>
<pre><code>## [1] "Date"
</code></pre>
<pre><code class="r">date1 <- '05/04/1989'
date1 <- as.Date(date1,format='%m/%d/%Y')
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-42" style="background:;">
<hgroup>
<h2>Date类型</h2>
</hgroup>
<article data-timings="">
<p>通常的输入格式是用短横隔开,如果是其它格式,则在as.Date函数内需要有format参数来确定。Date类数据可以进行常规的加减和比较。</p>
<pre><code class="r">date2 <- date1 + 31
date2 - date1
</code></pre>
<pre><code>## Time difference of 31 days
</code></pre>
<pre><code class="r">date2 > date1
</code></pre>
<pre><code>## [1] TRUE
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-43" style="background:;">
<hgroup>
<h2>Date类型</h2>
</hgroup>
<article data-timings="">
<p>时间类数据都是从1970年1月1日作为起始点计算。例如计算从那天开始直到现在的天数。</p>
<pre><code class="r">Sys.Date() - structure(0, class='Date')
</code></pre>
<pre><code>## Time difference of 16899 days
</code></pre>
<p>我们也可以创建一个日期向量,并进行计算。</p>
<pre><code class="r">dates <- seq(date1, length=4, by='day')
format(dates, '%w')
</code></pre>
<pre><code>## [1] "4" "5" "6" "0"
</code></pre>
<pre><code class="r">weekdays(dates)
</code></pre>
<pre><code>## [1] "星期四" "星期五" "星期六" "星期日"
</code></pre>
<p>如果需要了解更多日期的格式转换,可以参见strptime函数的帮助。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-44" style="background:;">
<hgroup>
<h2>POSIXct类型</h2>
</hgroup>
<article data-timings="">
<p>POSIXct类型的数据创建和计算是类似的。</p>
<pre><code class="r">time1 <- '1989-05-04'
time1 <- as.POSIXct(time1)
time1 <- "2011-03-1 01:30:00"
time1 <- as.POSIXct(time1,format="%Y-%m-%d %H:%M:%S")
time1 <- as.POSIXct("2011-03-1 01:30:00",tz='GMT')
time2 <- seq(from=time1,to=Sys.time(),by='month')
</code></pre>
<p>POSIXct类型的数据可以不包括时钟信息,或者在日期后加空格以冒号分隔时钟信息,也可以加上时区缩写。如果对输入格式有特别要求,可以使用format参数对输入格式进行设定,再行转换。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-45" style="background:;">
<hgroup>
<h2>POSIXct类型</h2>
</hgroup>
<article data-timings="">
<p>之前我们都是输入字符串再转为时间,这种方式有点繁琐,我们也可以直接从数值转为时间</p>
<pre><code class="r">time1 <- ISOdatetime(2011,1,1,0,0,0)
rtimes <- ISOdatetime(2013, rep(4:5,5), sample(30,10), 0, 0, 0)
</code></pre>
<p>ISOdatetime函数能将数值转为POSIXct时间对象,六个输入数值参数分别为年、月、日、时、分、秒。上面第二行代码使用了向量化特性,随机生成了10个时间。</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="segue dark" id="slide-46" style="background:;">
<hgroup>
<h2>字符串处理</h2>
</hgroup>
<article data-timings="">
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-47" style="background:;">
<hgroup>
<h2>字符串处理概要</h2>
</hgroup>
<article data-timings="">
<p>在文本数据挖掘日趋重要的背景下,在处理字符这种非结构化数据时,你需要能够熟练的操作字符串对象。</p>
<ul>
<li>获取字符串长度:<code>nchar()</code></li>