-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathipas-r-program.R
More file actions
1783 lines (1381 loc) · 39.5 KB
/
ipas-r-program.R
File metadata and controls
1783 lines (1381 loc) · 39.5 KB
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
# File : ipas-r-program.R
# Author : Ming-Chang Lee
# Date : 2011.07.04
# YouTube : https://www.youtube.com/@alan9956
# RWEPA : http://rwepa.blogspot.tw/
# GitHub : https://github.com/rwepa
# Email : alan9956@gmail.com
# reference: http://rwepa.blogspot.com/2013/01/r-201174.html
# 原檔名為 aMarvelousR_Lee(pp238).R, 用於 "A Marvelous R - Foundation", 2023.4.3 更名為 ipas-r-program.R
# 更新所有套件
update.packages(ask = FALSE, checkBuilt = TRUE)
# Updated : 2020.06.03 更新程式碼
# Updated : 2021.04.11 新增 Chapter 6. iPAS-R-program (Chapter 6.iPAS - 科目二:資料處理與分析概論)
# Updated : 2021.06.01 新增 Chapter 7. ggplot2 套件
# Updated : 2021.08.27 新增 Chapter 8. 繪圖中文字型
# Updated : 2021.12.17 新增 Chapter 9. 長寬資料轉換(tidyr, reshape2套件)
# Updated : 2021.12.25 新增 Chapter 10.安裝專案套件
# Updated : 2022.05.04 新增 Chapter 11.匯入SAS檔案
# Updated : 2022.09.12 新增 Chapter 12.dplyr 套件
# Updated : 2024.08.02 新增 Chapter 13.正規表示式
# Updated : 2024.08.02 新增 Chapter 14.YouBike2.0臺北市公共自行車即時資訊資料分析
# Updated : 2024.09.04 新增 Chapter 15.RMarkdown輸出中文PDF錯誤
# Updated : 2025.07.18 新增 Chapter 16.JAVA_HOME
# 大綱 -----
# Chapter 0. R筆記
# Chapter 1. Basic R
# Chapter 2. Preparing Data
# Chapter 3. Graphics
# Chapter 4. Applied Statistics
# Chapter 5. Application
# Chapter 6. iPAS - 科目二:資料處理與分析概論
# Chapter 7. ggplot2 套件
# Chapter 8. 繪圖中文字型
# Chapter 9. 長寬資料轉換(tidyr, reshape2套件)
# Chapter 10.安裝專案套件
# Chapter 11.匯入SAS檔案
# Chapter 12.dplyr 套件
# Chapter 13.正規表示式
# Chapter 14.YouBike2.0臺北市公共自行車即時資訊資料分析
# Chapter 15.RMarkdown輸出中文PDF錯誤
# Chapter 16.JAVA_HOME
# Chapter 0. R筆記 -----
# 2024.11.23
# fviz_nbclust {factoextra}: 估計集群法最佳集群個數與視覺化繪圖.
# Chapter 1. Basic R -----
# Change language settings
Sys.setenv(LANG = "en")
# p.10
# hist and plot
x <- c(1:100)
y <- rnorm(100)*100
hist(y)
test.model <- lm(y ~ x)
test.model
plot(x,y)
library(help="graphics")
# Understanding Diagnostic Plots for Linear Regression Analysis
# https://data.library.virginia.edu/diagnostic-plots/
# updated: 2022.9.27
# On-line help
?rnorm
?plot
#Information on package 'base'
library(help="base")
# end
# p.22
x <- c(1:10)
summary(x)
# end
# P.27
library(qcc)
?qcc
# p.28
# X-bar quality control chart
# load qcc library
library(qcc)
data(pistonrings)
attach(pistonrings)
pistonrings
diameter <- qcc.groups(diameter, sample)
qcc(diameter[1:25,], type="xbar")
# end
# TRY!
head(pistonrings)
head(pistonrings, n=3)
tail(pistonrings)
# end
# Chapter 2. Preparing Data -----
# p.40
# mode and length
x <- c(1:10)
mode(x)
length(x)
# end
# p.41
# name of object
A <- "WEPA"; compar <- TRUE; z <- 3+4i
mode(A); mode(compar); mode(z)
# end
# p.43
# Special numbers: Inf, -Inf, NaN, NA
x <- 5/0
x
exp(x)
exp(-x)
x - x
0/0
# NA
x.NA <- c(1,2,3)
x.NA
length(x.NA) <- 4
x.NA
# end
# p.46
# Joining (concatenating) vectors: c
x <- c(2,3,5,2,7,1)
x
y <- c(10,15,12)
y
z <- c(x, y)
z
# end
# p.47
# Subsets of vectors: Specify the numbers of the elements
# that are to be extracted
# Assign to x the values 3, 11, 8, 15, 12
x <- c(3,11,8,15,12)
# Extract elements no. 2 and 4
x[c(2,4)]
# Use negative numbers to omit elements:
x[-c(2,4)]
# Generate a vector of logical (T or F)
x > 10
# Subset for user's defined conditions
x[x > 10]
# Vectors have named elements- method 1
c(ALAN=100, SERENA=2000, ANDY=300, ALPHA=400)[c("ALAN","ANDY")]
# Vectors have named elements- method 2
score <- c(ALAN=100, SERENA=2000, ANDY=300, ALPHA=400)
score[c("ALAN","ANDY")]
# end
# p.49
# Regular sequences: seq
x1 <- 1:100
x2 <- 100:1
x3 <- seq(1,10, 0.5)
x4 <- seq(length=9, from=1, to=5)
x5 <- c(1,2,2.5,6,10)
# Regular sequences: scan
x6 <- scan()
# p.50
# Regular sequences: rep
rep(1,5)
# Regular sequences: sequence
sequence(5)
# Error !!!
sequence(5,2)
# Now, it is correct for R-4.0.0.
# the concatenated sequences 1:5 and 1:2
sequence(c(5,2))
# the concatenated sequences 1:5, 1:2 and 1:3
sequence(c(5,2,3))
# end
# p.52
# gl
gl(3, 5)
gl(3, 5, length=30)
gl(2, 5, label=c("Male", "Female"))
# end
# TRY
x <- gl(3, 4, label=c("優良", "普通", "加油"), length=27)
x
# end
# p.54
# Built-in Constants
# Upper-case letters
x <- LETTERS
x
length(x)
# Lower-case letters
y <- x[-c(2:10)]
y
length(y)
# Three-letter abbreviations for the month names
monthname.abb <- month.abb
monthname.abb
monthname.abb[c(1:10)]
# English names for the months
monthname.full <- month.name
monthname.full
# Ratio of the circumference of a circle to its diameter
circle.area <- pi*10^2
circle.area
# end
# p.55
# NA
x <- c(pi, 1, 2,3)
x
x[c(2,4)] <- NA
x
is.na(x[2])
is.na(x[1])
# To replace all NAs by 0
x[is.na(x)] <- 0
x
# end
# p.58
# A vector of five numbers
v1 <- c(.29, .30, .15, .89, .12)
v1
class(v1)
typeof(v1)
# Coerces into a single type
v2 <- c(.29, .30, .15, .89, .12, "wepa")
v2
class(v2)
typeof(v2)
# vector(mode, length)
x1 <- vector(mode="numeric", length=1000000)
# View x1
head(x1)
# Verify a vector
is.vector(x1)
# vector
x2 <- c("Taiwan", "China", "USA")
x2
is.vector(x2)
# Expand the length of a vector
length(x2) <- 5
x2
# end
# p.61
# list
list.test1 <- list(1,2,3,4,5)
list.test1[1]
list.test1[[1]]
# Each element in a list may be given a name
product <- list(destination="Taipei",
dimensions=c(3,6,10),price=712.19)
product[2]
product[[2]]
product$price
# end
# list all available data sets
data()
head(cars,n=3)
pts <- list(x=cars[,1], y=cars[,2])
plot(pts)
# end
# p.64
# factor
f1 <- factor(1:3)
f2 <- factor(1:3, levels=1:5)
f3 <- factor(1:3, labels=c("A", "B", "C"))
f4 <- factor(letters[1:6], label="YDU")
f4
class(f4)
eye.colors <- factor(c("brown", "blue", "blue", "green",
"brown", "brown", "brown"))
eye.colors
levels(eye.colors)
# end
# p.66
# array
a1 <- array(letters)
class(a1)
dim(a1)
# array
a2 <- array(1:3, c(2,4))
a2
dim(a2)
length(a2)
a2[1, ] # select row 1
a2[, 4] # select column 4
# end
# p.67
# array
a3 <- array(data=1:24,dim=c(3,4,2))
a3
# end
# p.69
# matrix
matrix.data <- matrix(c(1,2,3,4,5,6),
nrow = 2, ncol = 3, byrow=TRUE,
dimnames = list(c("row1", "row2"), c("C1", "C2", "C3")))
matrix.data
# end
# p.71
# data.frame
x <- c(1:4); n <- 10; m <- c(10, 35); y <- c(2:4)
df1 <- data.frame(x, n)
df1
df2 <-data.frame(x, m)
df2
# end
# p.71
# TRY !
df3 <- data.frame(x, y) # ERROR
df4 <- data.frame(var1= rnorm(5), var2=LETTERS[1:5])
df4
# end
# p.72
# The data give the speed of cars and
# the distances taken to stop.
data(cars)
help(cars)
class(cars)
head(cars)
# end
# p.75
# Time-series
data.ts <- ts(c(2,5,4,6,3,7,9:8),start=c(2009,2),frequency=4)
data.ts
is.ts(data.ts)
start(data.ts)
end(data.ts)
frequency(data.ts)
deltat(data.ts) # 0.25(=1/4)
plot(data.ts, type="b")
# end
# p.79
# Accessing Data
x <- c(1:8)
# how many elements?
length(x)
# ith element, i=2
x[2]
# all but ith element, i=2
x[-2]
# first k elements, k=5
x[1:5]
# last k elements, k=5
x[(length(x)-5+1):length(x)]
# specific elements
x[c(1,3,5)]
# all greater than some value
x[x>3]
# biger than or less than some values
x[x<3 | x>7]
# which indices are largest
which(x==max(x))
# end
# p.82
# Import/Export data
# Create a data directory C:\R.data
# Get working directory
getwd()
# Set working directory
dir.create("C:/R.data")
workpath <- "C:/R.data"
setwd(workpath)
getwd()
# p.86
# Create a CSV file (C:\R.data\score.csv)
# in which each field is separated by commas.
# Import dataset
# https://github.com/rwepa/DataDemo/blob/master/score.csv
score1 <- read.table(file="score.csv", header= TRUE, sep=",")
# TRY !
# score1 <- read.table(file="score.csv", header= TRUE)
score1
dim(score1)
names(score1)
row.names(score1)
# Add new column data for mid_term
mid.term <- matrix(c(60,80,65,85,80,90,99), nrow=7, ncol=1,
byrow=FALSE, dimnames = list(c(),c("mid.term")))
mid.term
# Merge two data.frame( score1 and mid_term)
score2 <- data.frame(score1, mid.term)
score2
# Export dataset
write.table(score2 , file= "score.final.txt",
sep = "\t",
append=FALSE,
row.names=FALSE,
col.names = TRUE,
quote= FALSE)
# end
# Chapter 3. Graphics -----
# p.91
demo(graphics)
# end
# p.96
# plot
data(cars)
head(cars, n=3)
plot(cars) # x-axis:speed; y-axis: dist
# p.97
# use the variable symbol "$"
plot(cars$dist, cars$speed)
# p.98
plot(cars, type="b")
# end
# p.99
# Available colors (#657)
# colors()
plot(cars, type="b", pch=5, col="red",
xlab="Speed(mph)", ylab="Stop distance(ft)",
main="Speed and Stopping Distances of Cars",
sub= "Figure 1: Plotting demonstration")
# end
# p.100
# Barplot
CarArrived <- table(NumberOfCar <- rpois(100, lambda=5))
CarArrived
barplot(CarArrived)
barplot(CarArrived, col=rainbow(14))
#end
# p.101
# pie
# Sales ratio
pie.sales <- c(0.14, 0.30, 0.26, 0.15, 0.10, 0.05)
# Sales area
names(pie.sales) <- c("Taipei1", "Taipei2", "Taipei3", "Taichung",
"Kao", "Other")
# default colours
pie(pie.sales)
# end
# p.102
# pie with customized colour
pie(pie.sales, col = c("purple", "violetred1", "green3",
"cornsilk", "cyan", "white"))
# end
# p.103
# pie with density of shading lines
pie(pie.sales, density = c(5,20), clockwise=TRUE)
# end
# p.104
# Box-and-whisker plot(s) of the given (grouped) values.
mat <- cbind(Uni05 = (1:100)/21, Norm=rnorm(100), T5 = rt(100,df= 5),
Gam2 = rgamma(100, shape = 2))
head(mat)
boxplot(data.frame(mat), main = "boxplot")
# end
# p.106
# stem plot
mat <- round(rnorm(10,30,10),0)
mat
stem(mat)
# end
# p.108
# Customized plot for 6-Sigma Quality Level
z <- pretty(c(44,56), 50) # Find 50 equally spaced points
ht <- dnorm(z, mean=50,sd=1) # By default: mean=0, standard deviation=1
plot(z, ht, type="l", main="6-Sigma Quality Level",
xlab="Qualty characteristic", ylab="Quality Level" ,
axes=FALSE, xlim=c(42,58), ylim=c(0,0.5))
# Add axis
# 1=below, 2=left, 3=above and 4=right
axis(side=1, c(42:58),tick = TRUE)
axis(side=2, tick = TRUE)
# Add vertical line
# h=0: horizontal line(s);v=0: vertical line(s)
abline(v=c(44,50,56), lty=c(1,2,1), col=c("red","blue","red"))
# Add text
text(44,0.5,"LSL", adj = c(-0.2,0))
text(50,0.5,"T",adj = c(-0.2,0))
text(56,0.5,"USL",adj = c(-0.2,0))
# end
# p.111
# 3D plot
# scatterplot3d package
# setup plotting environment for 2 rows and 2 columns
# par(bg = "white")
op <- par(mfrow = c(2,2))
# method 1: scatterplot3d (type=point) - Parabola
library(scatterplot3d)
x <- seq(-3, 3, length = 30)
y <- x
f <- function (x,y) {a <- 9; a - x^2 - y^2}
scatterplot3d(x, y, f(x,y),
highlight.3d=TRUE, col.axis="blue",
pch=20,
main="Euclidean Utility Function - parabola, (type=point)",
xlab="X", ylab="Y", zlab="f(x,y)",
zlim=c(0,9),
col.grid="lightblue",
type="p"
)
# method 2: scatterplot3d (type=point)
library(scatterplot3d)
x <- seq(-3, 3, length = 30)
f <- function (x,y) {a <- 9; a - x^2 - y^2}
x1 <- rep(x, 30)
x2 <- rep(x, each=30)
znew <- f(x1, x2)
scatterplot3d(x1, x2, znew,
highlight.3d=TRUE, col.axis="blue",
pch=20,
main="Euclidean Utility Function, (type=point)",
xlab="X", ylab="Y", zlab="f(x,y)",
zlim=c(0,9),
col.grid="lightblue",
type="p"
)
# method 3: scatterplot3d (type=line)
library(scatterplot3d)
x <- seq(-3, 3, length = 30)
f <- function (x,y) {a <- 9; a - x^2 - y^2}
x1 <- rep(x, 30)
x2 <- rep(x, each=30)
znew <- f(x1, x2)
scatterplot3d(x1, x2, znew,
highlight.3d=TRUE, col.axis="blue",
pch=20,
main="Euclidean Utility Function (type=line)",
xlab="X", ylab="Y", zlab="f(x,y)",
zlim=c(0,9),
col.grid="lightblue",
type="l"
)
# method 4: persp
x <- seq(-3,3,length = 30)
y <- x
f <- function (x,y) { a <- 9; a-x^2-y^2}
z <- outer(x,y,f)
persp(x,y,z,zlim = range(c(-10:10), na.rm = TRUE),
expand=1,theta = 30, phi = 30,
col = "lightblue",ticktype="detailed",
xlab="X", ylab="Y", zlab="f(x,y)",
main="Euclidean Utility Function")
# method 5: misc3d (need "rgl" package)
# misc3d package
library(misc3d)
parametric3d(
fx = function(u, v) u,
fy = function(u, v) v,
fz = function(u, v) -9 - u^2 - v^2 ,
fill = FALSE,
color = "blue",
scale = FALSE,
umin = -3, umax = 3, vmin = -3, vmax = 3, n = 100)
# setup plotting environment to the default
# par(mfrow=c(1,1))
par(op)
# end
# p.120
# 3D plot - sample
?persp
demo(persp)
# end
# Chapter 4.Applied Statistics -----
# p.122
# descriptive statistics
# Set working directory
workpath <- "C:/R.data"
setwd(workpath)
# import data
score <- read.table(file="score.csv", header= TRUE, sep=",")
# view data
score
# end
# summary data
# TRY summary(score)
score[2]
score[, 2]
score[3, ]
score$quiz1
quiz1 <- score$quiz1
mean(quiz1)
max(quiz1)
min(quiz1)
# end
# standard deviation
std(quiz1) # error function
# solution 1
sqrt( sum( (quiz1 - mean(quiz1))^2 /(length(quiz1)-1)))
# solution 2
# user's function
std = function(x) sqrt(var(x))
std(quiz1)
# solution 3
sd(quiz1)
# end
# p.129
# sample- t.test
# H0: u=95, H1: u<>95
t.test.data <- rnorm(50, mean=100, sd=15)
t.test(t.test.data, mu=95)
# p value is small, reject H0
# end
# p.130
# wilcox.test(x, conf.int=TRUE)
wilcox.test.data <- rnorm(50, mean=100, sd=15)
wilcox.test(wilcox.test.data, conf.int=TRUE, conf.level=0.99)
# end
# p.133
# prop.test
prop.test(39,215,0.15)
# end
# p.135
# shapiro.test
shapiro.test(rnorm(100, mean = 5, sd = 3))
shapiro.test(runif(100, min = 2, max = 4))
# end
# p.139
# QQ plot without logarithmic transformation
# first: qqnorm, second: qqline
data(Cars93, package="MASS")
qqnorm(Cars93$Price, main="Q-Q Plot: Price")
qqline(Cars93$Price)
# QQ plot without logarithmic transformation
qqnorm(log(Cars93$Price), main="Q-Q Plot: log(Price)")
qqline(log(Cars93$Price), col=2)
# end
# p.145
# one-way anova
# Copy the data to C:\R.data
# Import data
# https://github.com/rwepa/DataDemo/blob/master/drink.csv
drink.sales <- read.table("drink.csv", header=TRUE, sep=",")
head(drink.sales)
# drink.type <- factor(gl(4,5,label=c(letters[1:4])))
drink.type <- gl(4,5,label=c(letters[1:4]))
drink.type
drink <- data.frame(drink.type=drink.type, drink.sales)
head(drink)
class(drink)
# method 1. oneway.test
drink.oneway <- oneway.test(drink$sales ~ drink$drink.type,
var.equal=TRUE)
drink.oneway
# method 2. aov
drink.anova <- aov(drink$sales ~ drink$drink.type)
summary(drink.anova)
# method 3. Linear model
drink.lm <- lm(drink$sales ~ drink$drink.type)
anova(drink.lm)
# end
# p.149
# linear regression
# Build-in data: cars
# x: speed, y: dist
head(cars)
dim(cars)
# linear model
cars.lm <- lm(dist~speed, data=cars)
summary(cars.lm)
# end
# regression information
anova(cars.lm)
coefficients(cars.lm)
coef(cars.lm)
confint(cars.lm)
deviance(cars.lm)
effects(cars.lm)
fitted(cars.lm)
residuals(cars.lm)
resid(cars.lm)
summary(cars.lm)
vcov(cars.lm)
# end
# residual plot
plot(dist ~ speed,
data = cars,
xlab = 'Speed',
ylab = 'Stopping distance',
main = 'Speed vs. Stopping distance for cars')
abline(cars.lm)
points(cars$speed, fitted(cars.lm), pch=18, col = "blue")
segments(cars$speed, cars$dist, cars$speed, fitted(cars.lm), col = "green")
# Chapter 5.Application -----
# p.157
# Rcmdr package
# install.packages("Rcmdr", dependencies=TRUE)
# p.160
# Run in native R, NOT FOR RSTUDIO.
library(Rcmdr)
# p.169
# View all available data sets
data()
# end
# p.171
# List the data sets in specific package
data(package="qcc")
# end
# p.174
# Load the data sets in specific package
data(pistonrings, package="qcc")
# end
# p.174
# TRY
# Select data with "sampe=1"?
pistonrings.sample1 <- pistonrings[pistonrings$sample == 1,]
pistonrings.sample1
# end
# P.177
# Help and column names
help("pistonrings")
names(pistonrings)
# end
# p.182
# set global options
x <- sqrt(2)
x
options(digits=16)
x
# end
# P.183
# 下載10萬筆測試資料
# https://github.com/rwepa/DataDemo/blob/master/R03_Orders.txt
# p.193
# Probability function
dnorm(1.96, 0, 1)
pnorm(1.96, 0, 1) # z --> p, 0.975
qnorm(0.975, 0, 1) # p --> z, 1.96
rnorm(5, 0, 1)
# T分配: pt, F分配: pf, chi-squared分配: pchisq, 指數分配: pexp, gamma分配: pgamma, Weibull分配: pweibull
dnorm(1.645)
pnorm(1.645)
pnorm(1.96)
pnorm(2)
qnorm(0.95, 0, 1)
# end
# p.194
# Random generation
# also runif(1,min=0,max=2)
runif(1,0,2)
runif(5,0,2)
# 5 random numbers in [0,1]
runif(5)
x <- runif(100) # get the random numbers U(0,1)
hist(x,probability=TRUE,col=gray(.9),main="uniform on [0,1]")
# end
# p.195
# Sample - binomial distribution
pbinom(3, 10, 0.1)
# end
# p.197
# Sample - normal distribution
pnorm(c(2.5), mean=0, sd=1, lower.tail=TRUE)
# end
# p.197
# The ppt is disabled.
# TRY P(Z<=a)=0.95
a <- qnorm(c(0.95), mean=0, sd=1, lower.tail=TRUE)
a
# end
# p.219
# Quality Control Chart
library(qcc)
workpath = "c:/rdata"
setwd(workpath)
# 先將資料複製到 C:\rdata 目錄
# 匯入資料
# https://github.com/rwepa/DataDemo/blob/master/hw1.csv
hw1 <- read.table("hw1.csv", header=TRUE, sep=",")
# 顯示資料
hw1
# 取出全部資料的第2-4欄
pcb <- hw1[, c(2:4)]; pcb
dim(pcb) # 包括 25列, 3行 資料
qcc(pcb, type="xbar") # 第22筆資料超出管制界限
qcc(pcb, type="R") # 第15筆資料超出管制界限
pcb.modified <- pcb[-c(15,22), ] # 移除第15,22筆資料
dim(pcb.modified) # 包括 23列, 3行 資料
qcc(pcb.modified, type="xbar") # 製程有在管制界限之內嗎?
qcc(pcb.modified, type="R") # 製程有在管制界限之內嗎?
# end
# p.233
# The example of R for Support Vector Machines(SVM)
# 安裝SVM 套件 e1071
# 載入套件 e1071
library(e1071)
library(mlbench)
# 載入資料集 Glass in mlbench package
# 資料集 214 個觀測值,9 個變數,第9 個數數名稱為Type,
# 有7 個種類(1:7)
data(Glass)
head(Glass)
# 設定變數index 為編號1,2,…214.
index <- 1:nrow(Glass)
# 準備隨機抽樣並設定測試資料的編號
# 利用sample 取樣,將資料的1/3 做為測試資料的序號
testindex <- sample(index, trunc(length(index)/3))
# 設定測試資料 testset,共71 筆資料
testset <- Glass[testindex, ]
# > dim(testset) # 可知道有71 筆測試資料
# 將其他資料設定訓練資料 trainset,共143 個筆資料
trainset <- Glass[-testindex, ]
# 利用svm 執行並將結果存入變數svm.model
svm.model <- svm(Type ~ ., data = trainset, cost = 100, gamma = 1)
# 利用predict 執行測試資料的分類預測
svm.pred <- predict(svm.model, testset[, -10])
print(svm.pred)
# 利用 write 輸出結果
# 將結果輸出成CSV 檔案
write.table(svm.pred, file = "svm.test.csv", sep = ",")
# end
# Chapter 6.iPAS - 科目二:資料處理與分析概論 -----
setwd("C:/rdata")
# 1-1資料組織與清理 -----
# KNN (K近鄰法) demo -----
library(animation)
# 設定動畫參數
ani.options(interval = 1, nmax = 10)
# 建立訓練集,測試集
set.seed(168)
df <- iris[iris$Species != "setosa",]
df$Species <- factor(df$Species)
ind <- sample(2, nrow(df), replace = TRUE, prob = c(0.8, 0.2))
traindata <- df[ind == 1, 3:4]
testdata <- df[ind == 2, 3:4]
# KNN示範
knn.ani(train = traindata, test = testdata, cl = df$Species[ind == 1], k = 20)
# Kmeans (集群法) demo -----
library(animation)
kmeans.ani()
# 資料標準化 -----
data(Cars93, package = "MASS")
# 直方圖
hist(Cars93$Price)
summary(Cars93$Price) # 原始資料 [7.4, 61.9]
# (0,1)標準化 -----
PriceMin <- min(Cars93$Price)