Professional Documents
Culture Documents
R - a brief introduction
Dzung Nguyen
Hoang Intended to interactively support research and data analysis projects
Department of Food
Technology
Exclusively licensed to Insightful (“S-Plus”)
R: Open source platform similar to S developed by R. Gentleman
BACH KHOA and R. Ihaka (U of Auckland, NZ) during the 1990s
University
Since 1997: international “R-core” developing team
Updated versions available every couple months
1 2
1
R basics R basics
Objects
objects names
naming convention types of objects: vector, factor, array, matrix, data.frame, ts, list
assignment attributes
functions mode: numeric, character, complex, logical
workspace length: number of elements in object
history creation
assign a value
create a blank object
5 6
R basics R basics
Naming convention
must start with a letter (A-Z or a-z) Assignment
can contain letters, digits (0-9), and/or periods “.” “<-” used to indicate assignment
case-sensitive x<-c(1,2,3,4,5,6,7)
mydata different from MyData x<-c(1:7)
do not use use underscore “_” x<-1:4
some names are already used by R (e.g. c, q, t, C, D, F, I, T) X = 1:4
and must be avoided ls(package:base)
7 8
2
R basics
Function
Let’s look at R
Dzung Nguyen
actions can be performed on objects using functions (note: a Hoang
9 10
Workspace
Function
during an R session, all objects are stored in a temporary,
working memory
11 12
3
History
during a session you can use the arrow keys to review the
command history Matrix
Data frame
13 14
15 16
4
Data Elements
17 18
19 20
5
Getting Started
To obtain and install R on your computer
Applied statistics and
Go to http://cran.r-project.org/mirrors.html to Probability for
Engineers
choose a mirror near you
Click on your favorite operating system (Linux, Mac,
or Windows)
Dzung Nguyen
Hoang
Department of Food
Vietnamese time
R
Technology
Download and install the “base”
BACH KHOA
University
To install additional packages
Start R on your computer
Choose the appropriate item from the “Packages”
BACH KHOA UNIVERSITY
menu Jan 2017
21 22
Ví dụ Vectơ
> Mydata <- c(2,3.5,-0.2) Vectơ (c=“concatenate”)
> x <- c(3,6,7,8) Tạo vectơ x > Colors <-
> mean(x) Hiển thị giá trị trung bình của x c("Red","Green","Red") Vectơ ký tự
> var(x) Hiển thị phương sai x
> y <- c(4.5,3,2,-0.5) Tạo một vectơ y > x1 <- 25:30
> plot(x,y) Tạo đồ thị x, y > x1
> x-y x-y đồ thị thành phần [1] 25 26 27 28 29 30 Chuỗi các số
> lm(y ~ x) Hồi quy tuyến tính y theo x
> x.matrix <- > Colors[2]
matrix(runif(9),ncol=3) Tạo một ma trận 3x3 [1] "Green" Chọn một thành phần
> solve(x.matrix) Nghịch đảo ma trận x.matrix
> cube <- function(z) > x1[3:5]
z^3 Tạo lập function “m3” [1] 27 28 29 Chọn nhiều thành phần
23 24
6
Thao tác với các phần tử Thao tác trên vectơ
> Mydata > x <- c(5,-2,3,-7)
[1] 2 3.5 -0.2 > y <- c(1,2,3,4)*10 Trên tất cả các thành phần
> y
> Mydata > 0 [1] 10 20 30 40
[1] TRUE TRUE FALSE
> sort(x) Sắp xếp một vectơ
> Mydata[Mydata>0] [1] -7 -2 3 5
[1] 2 3.5 Trích những thành phần dương
> order(x)
> Mydata[-c(1,3)] [1] 4 2 3 1 Trật tự các thành phần
[1] 3.5 Loại bỏ thành phần
> y[order(x)]
[1] 40 20 30 10
> rev(x) Nghịch đảo trật tự vectơ
[1] -7 3 -2 5
25 26
7
Các phép toán ma trận Các phép toán ma trận
> dim(x.mat) Chiều của ma trận Các chức năng hữu dụng khác:
[1] 3 2
> t(x.mat) Chuyển vị ma trận solve() Nghịch đảo một ma trận vuông
[,1] [,2] [,3] eigen() Vectơ và giá trị riêng của một ma trận vuông
[1,] 3 2 -3
> cbind(x.mat,x.mat)
[2,] -1 0 6
[,1] [,2] [,3] [,4]
[1,] 3 -1 3 -1
[2,] 2 0 2 0
> x.mat %*% t(x.mat) Nhân ma trận
[3,] -3 6 -3 6
[,1] [,2] [,3] > rbind(x.mat,x.mat[1,])
[1,] 10 6 -15 [,1] [,2]
[2,] 6 4 -6 [1,] 3 -1
[3,] -15 -6 45 [2,] 2 0
[3,] -3 6
[4,] 3 -1
29 30
8
Quản lý các objects Trợ giúp online
Tất cả các functions đều được mô tả chi tiết trong phần trợ giúp “on-line”.
ls()liệt kê các objects đã tạo
help.start() truy cập thư viện on-line trong WWW
ls(pat="m") liệt kê các objects có “m” trong tên. help(matrix) hoặc help("if") hoặc help("==")
ls(pat="^m") liệt kê các objects có tên bắt đầu bằng “m”. Hoặc ngắn gọn hơn
?matrix
rm() xóa objects
Sẽ mở ra một cửa sổ trợ giúp
33 34
> LETTERS[1:7]
[1] "A" "B" "C" "D" "E" "F" "G"
> letters[20:26]
[1] "t" "u" "v" "w" "x" "y" "z"
35 36
9
Một số functions hữu dụng Một số toán tử quan trọng
> x1 <- c(2,1,4,2,1,2) + - * /
> length(x1) Lũy thừa : 2^5 hoặc 2**5
[1] 6 Chia matrix: %/%
Mod: %% (7%%5 gives 2)
> unique(x1)
[1] 2 1 4
Các functions cơ sở: abs(), sign(), log(), log10(), sqrt(),
> table(x1) exp(), sin(), cos(), tan()
1 2 4 gamma(), lgamma(), choose()
2 3 2
37 38
10
Giá trị “thiếu”: NA “data frames”
Ký hiệu NA (“non-available”) được dùng để chỉ các đại lượng thiếu:
> x <- c(3.5,-1,4,6,-2,6,2) Ví dụ:
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
> x[c(3,6)] <- NA trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
> x group <- gl(2,10,20, labels=c("Ctl","Trt"))
[1] 3.5 -1.0 NA 6.0 -2.0 NA 2.0 weight <- c(ctl, trt)
> is.na(x) PlantWeight <- data.frame(Weight=weight,Group=group)
[1] FALSE FALSE TRUE FALSE FALSE TRUE FALSE PlantWeight
> x.sans.NA <- x[!is.na(x)] “data frames” có thể bao gồm cả biến
Weight Group
> x.sans.NA 1 4.17 Ctl số và biến chữ (gọi là « factor »).
[1] 3.5 -1.0 6.0 -2.0 2.0 2 5.58 Ctl
> mean(x) 3 5.18 Ctl dùng data.frame() hoặc
[1] NA ... as.data.frame() để khởi tạo.
> mean(x,na.rm=TRUE) 19 4.32 Trt
20 4.69 Trt
[1] 1.7
> c(1:length(x))[is.na(x)]
[1] 3 6
41 42
11
Cửa sổ graphics và function
plot()
Applied statistics and
Probability for > plot(rnorm(100),rnorm(100))
Engineers
Function rnorm()
3
Dzung Nguyen
Hoang Đồ thị trong R Tạo các biến ngẫu nhiên
theo luật chuẩn.
2
Department of Food
Technology
1
rnorm(100)
BACH KHOA
Tham khảo ?rnorm,
và ?runif,
0
University
?rexp,
-1
?binom, ...
-2
BACH KHOA UNIVERSITY
Jan 2017 -3 -2 -1 0 1 2
rnorm(100)
45 46
1. 0
0. 5
0. 0
0. 0
y
2.5
-0.5
-1.0
Georgia
> plot(x,y,type= "l",
x x
type= "n",xlab= "Murder", Hawaii Arkansas
ylab= "Illiteracy") Arizona North Carolina
main="Une Ligne")
Illiteracy
Tennessee
> text(state.x77[,5],state.x77[,3],
1.0
Kentucky
1.5
0. 5
Alaska
dimnames(state.x77)[[1]],
y[ seq(5, 100, by = 5)]
y[seq(5,100,by=5)],
-1.0
ConnecticutNew Jersey
Massachusetts Oklahoma California
type= "b",axes=F)
1.0
Pennsylvania
-2.0
> par(mfrow=c(1,1)) 2 4 6 8 10 12 14
47 Murder
48
12
Các functions dùng với plot() Các function graphics khác
> axis(1,at=c(2,4,5), (“ticks”, legend, …) Xem phần help online về các lệnh sau:
legend("A","B","C")) Dùng xaxt="n" hay yaxt="n" trong plot()
barplot()
> lines(x,y,…) Thêm một đường thẳng image()
hist() 8
pairs() 6
120
persp()
10
Z
2
0 5
đứng từ 2 và 3 piechart() -2
100
-10
0
Y
-5
polygon() 0 -5
80
5
dist
60
scatter.smooth()
40
> legend(locator(1),…) Legends: rất linh động, xem thêm help!
20
0
5 10 15 20 25
49 50
speed
2
1 x
1
f ( x | , )
0.3
Phân bố chuẩn:
Applied statistics and e 2
2
dnorm(x)
Probability for
0.2
Engineers
> dnorm(2,mean=1,sd=2) Giá trị mật độ
0.1
Dzung Nguyen
-4 -2 0 2 4
Hoang
Department of Food
Technology > qnorm(0.975) Đại lượng Quantile
[1] 1.959964 với xác suất 0.975 trung bình 0 và độ lệch chuẩn 1
BACH KHOA
University
> pnorm(c(2,3),mean=2) = P(X<2) et P(X<3), où X ~ N(2,1)
[1] 0.5000000 0.8413447
> norm.alea <- rnorm(1000) Tạo các số giả ngẫu nhiên theo phân bố chuẩn
> summary(norm.alea)
BACH KHOA UNIVERSITY Min. 1st Qu. Median Mean 3rd Qu. Max.
Jan 2017 -3.418 -0.6625 -0.0429 -0.01797 0.6377 3.153
> sd(norm.alea)
51 [1] 0.9881418 52
13
Một số ký hiệu cần nhớ Kiểm định giả thiết
Đối với phân bố chuẩn, phần gốc là norm sau đó bổ sung các chữ cái tùy trường hợp
Pour le test de Student (test t), qui permet de déterminer si deux
d để tính mật độ density ( dnorm() )
p để tính xác suất probability ( pnorm() ) moyennes de deux populations sont significativement différentes (au moins
q để tính quantiles ( qnorm() ) d’un point de vue statistique), utilisez la fonction t.test().
r để tạo số giả ngẫu nhiên theo phân bố chuẩn lựa chọn ( rnorm() ) Lisez attentivement sa documentation !
Phân bố Phần gốc Phần bổ sung Utilisez prop.test(), pour tester des hypothèses avec des proportions, ainsi
normale norm mean, sd, log que pour obtenir des intervalles de confiance pour des proportions.
loi t (Student) t df, log
uniforme unif min, max, log R contient quelques tests non paramétriques:
loi F (Fisher) f df1, df2
2 chisq df, ncp, log
binomiale binom size, prob, log wilcox.test() Test de rangs de Wilcoxon
exponentielle exp rate, log kruskal.test() Test de Kruskal-Wallis (analyse de variance à une voie
Poisson pois lambda, log non paramétrique)
... chisq.test() Test de 2 pour des tables de contigence
ks.test() Test de Kolmogorov-Smirnov pour l’adéquation
53 ... 54
BÀI TẬP
•Người ta đếm số lần đánh giá của mỗi thang điểm của nhóm đối
tượng đánh giá mức độ ưa thích sản phẩm A. Kết quả cho ở bảng
sau
14