You are on page 1of 14

History of R

Applied statistics and


Probability for
Engineers Statistical programming language S developed at Bell Labs since
1976 (at the same time as UNIX)

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

BACH KHOA UNIVERSITY


Jan 2017

1 2

What is R What is R does…


data handling and storage: numeric, textual
a programming “environment”
matrix algebra
object-oriented hash tables and regular expressions
similar to S-Plus high-level data analytic and statistical functions
freeware classes (“OO”)
provides calculations on matrices graphics
programming language: loops, branching, subroutines
excellent graphics capabilities
supported by a large user network
and does not ?
What is R NOT ? is not a database, but connects to DBMSs
has no graphical user interfaces, but connects to Java, TclTk
language interpreter can be very slow, but allows to call own C/C++
menu-driven
code
quick to learn no spreadsheet view of data, but connects to Excel/MsOffice
a program with a complex graphical interface no professional / commercial support
3 4

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

Applied statistics and


Probability for
Engineers

Function

Let’s look at R
Dzung Nguyen
 actions can be performed on objects using functions (note: a Hoang

function is itself an object) Department of Food


Technology
 have arguments and options, often there are defaults
 provide a result BACH KHOA
University
 parentheses () are used to specify that a function is being
called

BACH KHOA UNIVERSITY


Jan 2017

9 10

Workspace

Function
 during an R session, all objects are stored in a temporary,
working memory

R Workspace & History  list objects: ls()


 remove objects: rm()
 objects that you want to access later must be saved in a
“workspace”
 from the menu bar: File->save workspace
 from the command line: save(x,file=“MyData.Rdata”)

11 12

3
History

 command line history


 can be saved, loaded, or displayed Two most common object
savehistory(file=“MyData.Rhistory)
loadhistory(file=“MyData.Rhistory) type for statistics
history(max.show=Inf)

 during a session you can use the arrow keys to review the
command history Matrix
Data frame

13 14

Matrix Data frame

several modes allowed within a single data frame


can be created using data.frame()
a matrix is a vector with an additional attribute (dim) that
L<-LETTERS[1:4] #A B C D
defines the number of columns and rows
x<-1:4 #1 2 3 4
only one mode (numeric, character, complex, or logical)
data.frame(x,L) #create data frame
allowed
attach() and detach()
can be created using matrix()
the database is attached to the R search path so
x<-matrix(data=0,nr=2,nc=2)
that the database is searched by R when it is
x<-matrix(0,2,2)
evaluating a variable.
objects in the database can be accessed by simply
giving their names

15 16

4
Data Elements

select only one element


x[2]
select range of elements
x[1:3]
Data Import & Entry
select all but one element
x[-3]
slicing: including only part of the object
x[c(1,2,5)]
select elements based on logical operator
x(x>3)

17 18

Importing Data Data Entry & Editing

start editor and save changes


read.table()
•data.entry(x)
• reads in data from an external file
data.entry() start editor, changes not saved
• create object first, then enter data •de(x)
c() start text editor
• concatenate edit(x)
scan()
• prompted data entry
• R has ODBC for connecting to other programs

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

Ma trận Tách các thành phần của matrix


> x <- c(3,-1,2,0,-3,6) > x.mat[,2] Cột thứ 2
> x.mat <- matrix(x,ncol=2) Tạo ma trận có hai cột [1] -1 0 6
> x.mat (mặc định : theo cột)
> x.mat[c(1,3),] Hàng thứ 1 và 3
[,1] [,2]
[1,] 3 0
[,1] [,2]
[2,] -1 -3
[1,] 3 -1
[3,] 2 6
[2,] -3 6
> x.mat <- matrix(x,ncol=2,
> x.mat[-2,] Không có hàng thứ 2
byrow=T) Tạo ma trận theo hàng
> x.mat
[,1] [,2]
[,1] [,2]
[1,] 3 -1
[1,] 3 -1
[2,] -3 6
[2,] 2 0
[3,] -3 6
27 28

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

Liệt kê các đối tượng Liệt kê (tt)


> my.list <- list(c(5,4,-1),c("X1","X2","X3"))
> my.list > x.mat
[[1]]: [,1] [,2]
[1] 5 4 -1 [1,] 3 -1
[2,] 2 0
[[2]]: [3,] -3 6
[1] "X1" "X2" "X3"
> dimnames(x.mat) <- list(c("L1","L2","L3"),
c("R1","R2"))
> my.list[[1]]
[1] 5 4 -1
> x.mat
> names(my.list) <- c("c1","c2") R1 R2
> my.list$c2[2:3] L1 3 -1
[1] "X2" "X3" L2 2 0
L3 -3 6
> my.list <- list(c1=c(5,4,-1),c2=c("X1","X2","X3"))
31 32

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

Đọc trợ giúp “on-line” Một số functions hữu dụng


Introduction > seq(2,12,by=2)
[1] 2 4 6 8 10 12
Xem và thực hiện các > seq(4,5,length=5)
[1] 4.00 4.25 4.50 4.75 5.00
ví dụ phía cuối help
> rep(4,10)
[1] 4 4 4 4 4 4 4 4 4 4
Xem phần hướng dẫn > rep(1:3,1:3)
chi tiết sau [1] 1 2 2 3 3 3
> paste("V",1:5,sep="")
[1] "V1" "V2" "V3" "V4" "V5"

> 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

Làm tròn: round(x,3) làm tròn 3 số lẻ thập phân

Và: floor(2.5) cho ra 2, ceiling(2.5) cho ra 3

37 38

Các toán tử trên vectơ Các functions logic


> vec <- c(5,4,6,11,14,19)
> sum(vec) R có hai giá trị logics: TRUE (hay T) và FALSE (hay F).
[1] 59 Tương tự: min() max() Ví dụ: == bằng
> prod(vec) cummin() cummax() < nhỏ hơn
[1] 351120 > 3 == 4 > Lớn hơn
range() [1] FALSE
> mean(vec) <= nhỏ hơn hoặc bằng
> 4 > 3 >= lớn hơn hoặc bằng
[1] 9.833333
[1] TRUE != khác
> median(vec)
& “và” (“and”)
[1] 8.5 > x <- -4:3
> var(vec) | “hoặc” (“or”)
> x > 1
[1] 34.96667 [1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
> sd(vec) > sum(x[x>1])
[1] 5.913262 [1] 5
Chú ý sự khác nhau !
> summary(vec) > sum(x>1)
Min. 1st Qu. Median Mean 3rd Qu. Max. [1] 2
4.000 5.250 8.500 9.833 13.250 19.000
39 40

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

“Data frames” Nhập số liệu


> PlantWeight$Weight Chú ý: Để nhập số liệu, tạo các file dưới dạng text (e.g. via "Save as ..." sau đó
[1] 4.17 5.58 5.18 6.11 4.50 4.61 > PlantWeight[,1]
... "Text (tab delimited) (*.txt)" trong Excel):
Hoặc
> PlantWeight[, ”Weight"] V1 V2 V3
> attach(PlantWeight) O1 3.4 -2 A
Cho ra cùng kết quả !
> Weight O2 2.2 -2 B Function scan()
[1] 4.17 5.58 5.18 6.11 4.50 4.61 ... O3 3.2 -1 A có thể cần thiết !
O4 1.2 1 A
> detach()
> Weight Sau đó sử dụng function read.table() :
Error: Object ”Weight" not found > data <- read.table("donnees.txt",header=T,sep="\t")
> dim(data)
[1] 4 3
> names(PlantWeight)
Object data là một “data frame”.
[1] ”Weight" ”Group"
Ký hiệu "\t" cho biết rằng các số liệu cách nhau một tab.
Dùng sep="," nếu số liệu cách nhau bởi dấu phẩy,
43 hoặc sep=";" đối với các file *.csv. 44

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

Tính linh động của fonction


plot() Dựng graphics theo block
> x <- seq(-2*pi,2*pi,length=100) Une Ligne
> data(state) > dim(state.x77)
> y <- sin(x) [1] 50 8
1. 0

1. 0

> dimnames(state.x77)[[2]] Louisiana


0. 5

0. 5

> par(mfrow=c(2,2)) [1] "Population" "Income" "Illiteracy"


S inus de x

0. 0

0. 0
y

2.5

> plot(x,y,xlab="x”, [4] "Life Exp" "Murder" "HS Grad" Mississippi


-0.5

-0.5

ylab="Sinus de x") [7] "Frost" "Area” South Carolina


-1.0

-1.0

New Mexico Texas


-6 -4 -2 0 2 4 6 -6 -4 -2 0 2 4 6 > plot(state.x77[,5],state.x77[,3], Alabama
2.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)]

West Virginia VirginiaNew York


> plot(x[seq(5,100,by=5)],
0.0

cex=0.7) Rhode Island Florida


y

y[seq(5,100,by=5)],
-1.0

ConnecticutNew Jersey
Massachusetts Oklahoma California
type= "b",axes=F)
1.0

Pennsylvania
-2.0

Delaware Maryland Illinois


Michigan
-6 -4 -2 0 2 4 6 North Dakota Ohio Missouri

> plot(x,y,type="n", x[seq(5, 100, by = 5)] x


New Hampshire
Wisconsin
Maine
Minnesota Washington
NebraskaOregon
Colorado
Indiana
Idaho Wyoming
Kansas
Utah
Montana
Vermont

R có thể tạo vô số đồ thị !


0.5

ylim=c(-2,1) South Dakota


Iowa Nevada

> 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

>abline(h=0,v=c(2,3)) Thêm một đường bằng từ 0 và hai đường

120
persp()
10

Z
2
0 5

đứng từ 2 và 3 piechart() -2

100
-10
0

> abline(lsfit(x,y)) Thêm một đường hồi quy

Y
-5

polygon() 0 -5

> abline(0,1) Thêm một đường có độ dốc bằng 1 và tọa X

80
5

độ gốc bằng 0 library(modreg) 10


-10

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

Với R không cần bảng thống kê !


0.4

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

Các hàm thống kê [1] 0.1760327 au point 2 pour X ~ N(1,4)


0.0

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

Mức độ đánh giá Tần số


1 0
Hãy thể hiện số liệu trên 2 1
một đồ thị dạng cột
3 4
4 8
5 9
6 15
7 25
8 7
9 2
55

14

You might also like