You are on page 1of 154

GIỚI THIỆU VỀ R

Nguyễn Văn Viên

TP.HCM, 12/8/2021
Cài đặt

Nhập liệu

Quản lý dữ liệu

Thống kê mô tả

Nội dung Logit/Probit model

Multinomial regression models (MRM)

Ordered multinomial models (OMM)

Poisson Regression Models (PRM)


Tài liệu tham khảo
• Gujarati, D. (2014). Econometrics by example. Macmillan.
• Nguyễn Thành Cả và Nguyễn Thị Ngọc Miên. Giáo trình Kinh tế lượng.
https://sites.google.com/site/kinhteluongttkueh/home. Trường Đại học Kinh tế TP.HCM.
• Nguyễn Quang Dong và Nguyễn Thị Minh. Giáo trình Kinh tế lượng. Trường Đại học Kinh tế Quốc dân.
• Nguyễn Văn Tuấn (?). Phân tích số liệu và biểu đồ bằng R.
https://cran.r-project.org/doc/contrib/Intro_to_R_Vietnamese.pdf.
• Nguyễn Văn Tuấn (2019). Phân Tích Dữ Liệu Với R. NXB Tổng hợp TP.HCM.
• Nguyễn Văn Tuấn (2020). Mô hình hồi quy và Khám phá Khoa học. NXB Tổng hợp TP.HCM.
• Hanck, C., Arnold, M., Gerber, A., & Schmelzer, M. (2019). Introduction to Econometrics with R.
University of Duisburg-Essen. https://www.econometrics-with-r.org/index.html.
• Wooldridge, J. M. (2015). Introductory econometrics: A modern approach. Cengage learning.
• Hosmer Jr, D. W., Lemeshow, S., & Sturdivant, R. X. (2013). Applied logistic regression (Vol. 398). John
Wiley & Sons.
• Baltagi, B. H. (2021). Econometric analysis of panel data. Springer Nature.
R là "statistical and graphical programming
language".

R: do Ross Ihaka và Robert Gentleman (ĐH


Auckland, New Zealand) viết vào thập niên 1990s.

Sơ lược về Đến nay, R Core Team gồm 25 người.

R R có thể thực hiện các mô hình phân tích thống


kê, mô phỏng, vẽ đồ thị và biểu đồ, và lập trình.

R cấu trúc theo package.


Cài đặt R
• Tải file (cho Windows, MacOS) từ trang chủ của R, cài đặt, và có giao diện như sau:
Cài đặt RStudio
• Tải file (cho Windows, MacOS) từ trang chủ của RStudio, cài đặt, và có giao diện như
sau:
R vs. RStudio
Cài đặt package
• Gõ lệnh vào RStudio:
Ví dụ: Để cài đặt gói gdata, gõ lệnh như sau:
install.packages("gdata")

• Một số gói của R để sử dụng phải phụ thuộc vào một hoặc một số gói
khác, do đó nên thêm tùy chọn "dependencies = TRUE". Câu lệnh mới
là:
install.packages("gdata", dependencies = TRUE)
Gọi package cần sử dụng
• Gõ lệnh vào RStudio:
Ví dụ 1: Để gọi gói gdata (đọc file .xls), gõ lệnh như sau:
library(gdata)

•Ví dụ 2: Hãy thử cài đặt và gọi các gói sau: xlsx, readxl, foreign,
hexView
Tạo R script
• Mở RStudio
• Cách 1: File  New File  R Script
• Cách 2: Click biểu tượng "New File" trên thanh Toolbar  chọn R Script
• Cách 3: Ctrl + Shift + N
• Dấu # bắt đầu cho ghi chú.
Quy ước khi sử dụng R
• Để tất các file dữ liệu vào thư mục cố định.
• Tại mỗi thời điểm R mặc định chỉ làm việc với một thư mục, do đó luôn gõ lệnh bên dưới
sau khi khởi động R để chỉ thị cho R làm việc với thư mục trên.
setwd("G:/My Drive/3. Others/UEH - CDEA/10. Tai lieu lop hoc/1. Kinh te luong ung
dung/Gujarati 2014/Zipped data sets v2/Excel")
• Kiểm tra thư mục đang làm việc bằng cách:
getwd()
• Liệt kê objects đang làm: ls()
• Kết quả tính toán được lưu trong objects, dùng = hoặc <-. Tuy nhiên, dấu = có thể gây
một số lỗi khi thực hiện một số lệnh và hàm.
• R phân biệt chữ viết hoa và viết thường.
Về
"attach"
Grolemund, G. (2014).
Hands-on programming
with R: write your own
functions and simulations.
"O'Reilly Media, Inc.".
Nhập liệu trực tiếp (1)
ST X2 X3 Y
T (Lương) (Thu nhập khác) (Chi tiêu)
1 20 16 24.4
2 30 10 31.2
3 28 2 29.2
4 24 0 23.6
5 32 18 36.0
6 36 10 31.4
7 32 16 32.6
8 34 24 36.8
9 24 28 32.8
10 22 20 29.8
11 28 8 30.2
12 30 4 26.8
Nhập liệu trực tiếp (2)
luong = c(20, 30, 28, 24, 32, 36, 32, 34, 24, 22, 28, 30)
thunhapkhac = c(16, 10, 2, 0, 18, 10, 16, 24, 28, 20, 8, 4)
chitieu = c(24.4, 31.2, 29.2, 23.6, 36, 31.4, 32.6, 36.8, 32.8, 29.8, 30.2, 26.8)

Ghi chú: c = concatenate/ concatenation (ghép lại)

Nếu nhập sai, chỉnh sửa dữ liệu bằng cách:


luong = edit(luong)

Xem lại dữ liệu bằng cách gõ tên đối tượng:


luong
Nhập liệu từ file có sẵn
Hãy thử cài đặt các gói sau vào R (nếu chưa có), và xem qua phần HDSD các gói
này.
Tên gói Công dụng
xlsx Đọc data đuôi .xlsx (file Excel)
gdata Đọc data đuôi .xls (file Excel)
readxl Đọc data đuôi .xls và .xlsx (file Excel)
Đọc data đuôi .sav (file SPSS), .dta (file Stata 12 trở
foreign
xuống)
readstata13 Đọc data đuôi .dta (file Stata 13, 14)
haven Đọc data đuôi .dta (file Stata 13, 14), .sav (file SPSS)
hexView Đọc data đuôi .wf1 và .WF1(file Eviews)
Đọc dữ liệu từ Excel
Cách 1:
• library(gdata) # Gọi gói "gdata" đọc file .xls
• test = read.xls("Table2_8.xls") # Đọc file .xls

Cách 2:
• library(readxl) # Gọi gói "readxl" đọc file .xls, .xlsx
• test = read_excel("luong.xlsx", sheet = 1) # Đọc file .xls hoặc .xlsx, sheet 1
Đọc dữ liệu file .csv
Cách 1:
• test = read.csv("debt.csv", header = TRUE) # Đọc file .csv

Cách 2:
• library(readr) # Gọi gói "readr" đọc file .csv nhanh hơn
• test = read_csv("debt.csv") # Đọc file .csv
• test = fread("debt.csv") # Đọc dữ liệu có kích thước rất lớn

So sánh thời gian đọc file:


• system.time(test <- read.csv("flights.csv")) # Cách 1: dùng lệnh thông thường
• library(data.table) # Cách 2: dùng gói "data.table"
• system.time(test <- fread("flights.csv"))
Đọc dữ liệu từ Stata (1)
• library(foreign) # Gọi gói "foreign" đọc file Stata 12 trở xuống

• test = read.dta("Panel1.dta") # Đọc file "Panel1.dta"

• test # Xem dữ liệu trong object "test"

• head(test) # Xem 6 dòng đầu của object "test"

• tail(test) # Xem 6 dòng cuối của object "test"

• dim(test) # Xem số lượng quan sát và biến số

• str(test) # Mô tả chi tiết kiểu biến số của data frame


Đọc dữ liệu từ Stata (2)
• library(readstata13) # Gọi gói "readstata13" đọc file Stata 13, 14

• test = read.dta13("test_stata13.dta") # Đọc file "test_stata13.dta"

• library(haven) # Gọi gói "haven" đọc file Stata 13, 14

• test = read_stata("test_stata13.dta") # Đọc file "test_stata13.dta"


Đọc dữ liệu từ SPSS
Cách 1:
• library(foreign) # Gọi gói "foreign" đọc file SPSS

• test = read.spss("chicken.sav", to.data.frame = TRUE) # Đọc file "chicken.sav"

Cách 2:
• library(haven) # Gọi gói "haven" đọc file SPSS

• test = read_spss("chicken.sav") # Đọc file "chicken.sav"

• test = read_sav("chicken.sav") # Đọc file "chicken.sav"


Đọc dữ liệu từ Eviews
• library(hexView) # Gọi gói "hexView" để đọc file Eviews

• test = readEViews("ch2vd5.WF1") # Đọc file ch2vd5.WF1

• test # Xem dữ liệu trong object "test"

• head(test) # Xem 6 dòng đầu của object "test"

• tail(test) # Xem 6 dòng cuối của object "test"

• dim(test) # Xem số lượng quan sát và biến số

• str(test) # Mô tả chi tiết kiểu biến số của data frame


Quản lý dữ liệu (1)
• Tạo data frame
test = data.frame(luong, thunhapkhac, chitieu) # Tạo data frame với 3 biến số đã tạo sẵn

test = data.frame(x2 = c(10, 15, 18, 24, 30),


x3 = c(50, 75, 90, 120, 150),
x4 = c(52, 75, 97, 129, 152)) # Tạo data frame với 3 biến số

X2 X3 X4
10 50 52
15 75 75
18 90 97
24 120 129
30 150 152
Quản lý dữ liệu (2)
• Tạo data frame
test = edit(data.frame()) # Mở data frame và nhập dữ liệu

• Chỉnh sửa dữ liệu


test = edit(test)
Thay đổi nhãn của quan sát (1)
• Ví dụ: Data frame "ch4bt8.wf1" có biến URBAN với mô tả như sau:
URBAN = 1: đô thị
URBAN = 0: nông thôn

library(hexView)
test = readEViews("ch4bt8.wf1")
test$khuvuc[test$URBAN == 1] = "Dothi" # Tạo biến mới "khuvuc"
test$khuvuc[test$URBAN == 0] = "Nongthon" # khuvuc = Dothi nếu URBAN = 1
# khuvuc = Nongthon nếu URBAN = 0
• Xóa biến URBAN:
test$URBAN = NULL
Thay đổi nhãn của quan sát (2)
• Một cách khác:
test$URBAN[test$URBAN == 1] = "Dothi" # Đổi nhãn của quan sát thành Dothi nếu
URBAN = 1
test$URBAN[test$URBAN == 0] = "Nongthon" # Đổi nhãn của quan sát thành Nongthon
nếu URBAN = 0
• Ví dụ: Hãy thử biến đổi ngược lại

• Một cách khác:


test$MALE = factor(test$MALE, levels = c("1", "0"), labels = c("Male", "Female"))
test$MARRIED = factor(test$MARRIED, levels = c("1", "0"), labels = c("Yes", "No"))
test$BLACK = factor(test$BLACK, levels = c("1", "0"), labels = c("Black", "White"))
test$SOUTH = factor(test$SOUTH, levels = c("1", "0"), labels = c("South", "North"))
Thay đổi nhãn của quan sát (3)
• Phân loại nhóm thu nhập (theo một tiêu chuẩn) cho các quan sát. Giả sử tiêu
chuẩn đó là:
• Thấp hơn hoặc bằng 3200: nhóm thu nhập thấp
• Từ 3200 đến nhỏ hơn hoặc bằng 3500: nhóm thu nhập trung bình
• Lớn hơn 3500: nhóm thu nhập khá

• Ví dụ: dùng lệnh ifelse()


test$Class = ifelse(test$WAGE <= 3200, "Thap", ifelse(test$WAGE > 3200 &
test$WAGE <= 3500, "Trungbinh", ifelse(test$WAGE > 3500, "Kha", "Thap")))

table(test$Class)
Ghép dữ liệu vào một data frame sẵn có
(1)
• Data frame sẵn có: test = data.frame(luong, thunhapkhac, chitieu)

• Data frame mới:


test2 = data.frame(luong = c(31, 30), thunhapkhac = c(7, 10), chitieu = c(23, 28))

• Dùng lệnh rbind():


test3 = rbind(test, test2) # "r" = row
Ghép dữ liệu vào một data frame sẵn có
(2)
• Nếu 14 quan sát ở trên có 8 quan sát đầu thuộc khu vực thành thị (kí hiệu TT) và 6
quan sát sau thuộc khu vực nông thôn (kí hiệu NT):
khuvuc = c(rep("TT", 8), rep("NT", 6)) # rep: lặp lại dữ liệu
test3 = cbind(test3, khuvuc) # Ghép cột ("c" = column)

• Lệnh merge()
df1 = data.frame(Name = c("Hoa", "Linh", "Nam"), Age = c(18, 21, 20))
df2 = data.frame(Name = c("Hoa", "Linh", "Nam"), Score = c(19, 26, 24), Gender = c("F",
"F", "M"))
total = merge(df1, df2, by.x = "Name") # Cách 1
total = merge(df1, df2) # Cách 2
Lọc dữ liệu với lệnh filter (1)
• Ví dụ: thực hành trên bộ dữ liệu CPS1988 trong gói AER.
install.packages("AER") # Cài đặt gói AER
library(AER)
data("CPS1988") # Gọi bộ dữ liệu CPS1988
library(dplyr) # Gọi gói dplyr
Lọc dữ liệu với lệnh filter (2)
• Lọc ra các quan sát có education lớn hơn 12 và biến định tính smsa nhận giá trị "no":
df1 = filter(CPS1988, education > 12 & smsa == "no")

• Lọc ra các quan sát đến khu vực miền nam và tây:
df2 = filter(CPS1988, region == "south" | region == "west") # Cách 1
df3 = filter(CPS1988, region %in% c("south", "west")) # Cách 2
df4 = filter(CPS1988, region != "northeast" & region != "midwest") # Cách 3
Chọn cột biến với lệnh select
• Chỉ giữ lại hai biến là wage và education:
df5 = select(CPS1988, wage, education)
• Chuyển hai biến là smsa và region lên vị trí thứ nhất và giữ nguyên các biến còn lại:
df6 = select(CPS1988, smsa, region, everything())

df7 = select(CPS1988, -smsa) # Loại biến smsa

df8 = select(CPS1988, education:smsa) # Lấy các biến từ education đến smsa

df9 = select(CPS1988, starts_with("e")) # Lấy các biến bắt đầu bằng chữ "e"
df10 = select(CPS1988, starts_with("E"))

df11 = select(CPS1988, ends_with("n")) # Lấy các biến kết thúc bằng chữ "n"
Đổi tên biến với lệnh rename
df12 = rename(CPS1988, luong = wage, giaoduc = education)

Sắp xếp lại theo giá trị tăng dần hay giảm
dần với lệnh arrange
df13 = arrange(CPS1988, desc(wage))
• Nếu có dữ liệu trống thì các giá trị trống sẽ được xếp ở dưới cùng.
• Nếu không có desc(wage) thì bộ số liệu được sắp xếp theo chiều tăng của wage.
Tạo biến mới với lệnh mutate và
transmute
• Biến wage trong bộ số liệu gốc đo mức lương tuần theo đơn vị USD. Nếu muốn tạo biến
mới với tên wage_1000 đo mức lương tuần theo đơn vị là 1000 USD thì:
df14 = mutate(CPS1988, wage_1000 = wage / 1000)

• Giả sử: tuổi của người lao động bằng năm đi học cộng với năm kinh nghiệm và cộng
thêm 6 (giả thiết dân Mỹ đi học lớp 1 từ lúc 6 tuổi):
df15 = mutate(CPS1988, age = education + experience + 6)

• Tạo biến mới dựa trên các biến cũ, và tách thành dataset mới:
df16 = transmute(CPS1988, luong = wage / 1000, age = education + experience + 6, khuvuc
= region)
Lọc ngẫu nhiên dữ liệu
library(dplyr) # Dùng gói "dplyr" để lọc dữ liệu
df17 = sample_n(CPS1988, 5) # Lấy ra ngẫu nhiên 5 quan sát
df18 = sample_frac(CPS1988, 0.01) # Lấy ra ngẫu nhiên 1% quan sát từ dữ liệu gốc
Lọc không ngẫu nhiên dữ liệu
a = slice(CPS1988, 1:3) # Cắt dữ liệu dòng 1  3
b = slice(CPS1988, 5:7) # Cắt dữ liệu dòng 5  7
c = slice(CPS1988, c(100, 200)) # Cắt dữ liệu dòng 100 và 200
Hợp nhất dữ liệu bằng lệnh bind_rows và
bind_cols
all = bind_rows(a, b, c) # Hợp nhất dữ liệu theo dòng
d = data.frame(uni = c("yes", "no", "no"), chil = c(1, 2, 4))
# Thử tạo một data frame mới
ad = bind_cols(a, d) # Hợp nhất dữ liệu theo cột
Lưu các dữ liệu trong R thành file Excel,
Stata
• Có thể lưu dữ liệu này về máy bằng cách:
setwd() # Xác định thư mục làm việc của R
write.csv(CPS1988, "CPS1988.csv") # Lưu dữ liệu dưới tên CPS1988.csv
write.xlsx(CPS1988, "CPS1988.xlsx") # Lưu dữ liệu dưới tên CPS1988.xlsx
write.dta(CPS1988, "CPS1988.dta") # Lưu dữ liệu dưới tên CPS1988.dta
Bài tập: Quản lý dữ liệu với R
• Nhập dữ liệu về tình hình Covid-19 hiện nay ở Việt Nam theo tỉnh/thành, gồm các biến số
sau:
• Tên tỉnh/thành
• Dân số của tỉnh/thành tính đến hết năm 2020 (từ GSO)
• Số ca nhiễm bệnh
• Số lượng vắc xin được phân bổ (a)
• Số lượng vắc xin đã tiêm (b)
• Đọc file dữ liệu vào R.
• Tạo biến tỷ lệ tiêm trên số lượng đã phân bổ.
• Tạo biến tỷ lệ nhiễm trên 1000 người.
• Tạo biến nguy cơ để phân nhóm tỉnh/thành theo số lượng ca nhiễm (cụ thể: từ 10.000 ca
trở lên = "Cao", từ 5.000- dưới 10.000 ca = "Trung bình", và dưới 5.000 ca = "Thấp").
• Lọc những tỉnh/thành có nguy cơ "thấp" và tỷ lệ tiêm từ 50% trở lên, thành dataset mới.
• Sản phẩm: R script, và các file dữ liệu.
Thống kê mô tả (1)
Hàm/Lệnh Chức năng
mean() Kỳ vọng (hay trung bình) của biến/các biến
sd() Độ lệch chuẩn của biến/các biến
var() Phương sai của biến/các biến
cor() Ma trận hệ số tương quan của các biến
summary() Đưa ra 6 thống kê cơ bản cho biến/các biến số
max() Giá trị lớn nhất của các biến số
min() Giá trị nhỏ nhất của các biến số
quantile() Ngũ phân vị
Thống kê mô tả (2)
library(hexView)
test = readEViews("ch2_health.WF1", as.data.frame = TRUE)
summary(test) # Xem các thống kê cơ bản của tất cả các biến
cor(test) # Bảng ma trận hệ số tương quan giữa các biến số
summary(test$INCOME) # Nếu chỉ quan tâm 1 biến số
quantile(test$INCOME)
sapply(test, quantile) # Ngũ phân vị cho tất cả các biến số

 Dùng ký hiệu "$" để R hiểu cần phân tích biến "INCOME" của dataset "test".
Thống kê mô tả biến phân nhóm
install.packages("gmodels") # Cài package gmodels
library(gmodels)
library(AER)
data("CPS1988")
CrossTable(CPS1988$region, digits = 3) # Một biến
CrossTable(CPS1988$region, CPS1988$ethnicity, digits = 2)# Hai biến
Thống kê mô tả chi tiết với gói pastecs
install.packages("pastecs")
library(pastecs)
options(digits = 4) # Hiển thị các kết quả chính xác đến 4 chữ số sau dấu phẩy
stat.desc(test) # Thống kê mô tả
stat.desc(test, desc = F) # Thu gọn kết quả thống kê mô tả
Thống kê mô tả chi tiết với gói stargazer
install.packages("stargazer")
library(stargazer)
stargazer(test, type = "text", title = "Cac Thong Ke Mo Ta", digits = 3)
# Thống kê mô tả
stargazer(test, type = "text", title = "Cac Thong Ke Mo Ta", digits = 3, out = "ketqua.doc")
# Xuất kết quả ra file "ketqua.doc"
Thống kê mô tả chi tiết với gói fBasics
install.packages("fBasics")
library(fBasics)
basicStats(test) # Thống kê mô tả
options(digits = 3) # Hiển thị các kết quả chính xác đến 3 chữ số sau dấu phẩy
basicStats(test$INCOME) # Thống kê mô tả cho 1 biến, không hiện kết quả
Đồ thị và biểu đồ
• Với gói mặc định graphic của R
• Với gói ggplot2
• Gồm:
Scatter plot
Đường hồi quy
Histogram
Hàm mật độ xác suất Density
Biểu đồ cột
Biểu đồ đường
Box plot…
Scatter plot
• Vẽ scatter plot với education trên trục X và log(wage) trên trục Y:
library(AER)
data("CPS1988") # Gọi bộ dữ liệu CPS1988
plot(log(wage) ~ education, data = CPS1988, col = "blue")
Đường hồi quy
• Vẽ đường hồi quy cho mô hình ln(wage) = β + β2education trên cùng với scatter plot ở
trên.
abline(lm(log(wage) ~ education, data = CPS1988), col = "red")
Histogram
• Vẽ histogram cho ln(wage) theo 6 cách thức khác nhau (chú ý hiệu ứng của những câu
lệnh này):
par(mfrow = c(2, 3))
hist(log(CPS1988$wage), col = "pink")
hist(log(CPS1988$wage), col = "blue", main = "") # Không đặt tên cho graph
hist(log(CPS1988$wage), col = "green", main = "Histogram cua log(wage)")
# Đặt tên cho graph
Histogram
• Vẽ histogram cho ln(wage) theo 6 cách thức khác nhau (chú ý hiệu ứng của những câu
lệnh này):
hist(log(CPS1988$wage), col = "yellow", main = " ", xlab = "Truc X", ylab = "")
# Đặt tên cho trục X
hist(log(CPS1988$wage), main = " ", xlim = c(3, 10), ylim=c(0, 10000), density = 20)
# Đặt giới hạn cho trục X từ 3 đến 10, Y từ 0 đến 10000
hist(log(CPS1988$wage), col = rainbow(8), main = "", border = F, prob = T)
# Không tô đường viền cho các class, hiển thị tần suất tương đối
của mỗi lớp đồng thời tô màu cho mỗi lớp mô phỏng màu cầu vồng
par(mfrow=c(1, 1)) # Trả lại chế độ hiển thị bình thường
Hàm mật độ xác suất Density
par(mfrow=c(1, 2))
d = density(log(CPS1988$wage))
plot(d, main = "")
plot(d, main = "", frame = FALSE)
polygon(d, col = "steelblue")
par(mfrow = c(1, 1))
Hàm mật độ xác suất Density
• Kết hợp vẽ hàm mật độ xác suất và histogram:
hist(log(CPS1988$wage), main="", density = 20, prob = T, ylim = c(0, 0.7))
lines(d, col = "blue")
Biểu đồ cột
• Vẽ biểu đồ cột (bar plot) cho số
quan sát theo khu vực địa lý:
test = table(CPS1988$region)
install.packages("fBasics") #
Cài gói "fBasics"
library(fBasics) # Gọi
gói "fBasics"
mausac = qualiPalette(2,"Set3")
# Màu tự động
barplot(test, col = mausac, main =
"Phan bo dan so theo khu vuc")
Biểu đồ cột
• Biểu đồ cột theo cả khu vực địa lý
và sống ở khu vực đô thị hay phi đô
thị:
test = table(CPS1988$smsa,
CPS1988$region)
barplot(test, col = mausac, main =
"Ty le do thi hoa o cac vung")
legend("topright", legend =
rownames(test), box.lty = 0, cex = 1,
fill = mausac)
Biểu đồ cột
• Biểu đồ cột theo cả khu vực địa lý
và sống ở khu vực đô thị hay phi đô
thị:
test = table(CPS1988$smsa,
CPS1988$region)
barplot(test, col = mausac, main =
"Ty le do thi hoa o cac vung", beside
= TRUE, horiz = TRUE)
legend("topright", legend =
rownames(test), box.lty = 0, cex = 1,
fill = mausac)
Box plot
library(AER)
data(CPS1988) # Ví dụ với dữ liệu CPS1988
boxplot(log(CPS1988$wage) ~ CPS1988$region) # Box plot cho ln(wage) đồng thời
cho cả 4 vùng địa lý khác nhau
Box plot
boxplot(log(CPS1988$wage) ~ CPS1988$region, col = c("blue", "sienna", "palevioletred1",
"green")) # Tô màu cho box plot
Pie chart
pie(table(CPS1988$region), col = c("pink", "orange", "green", "blue"))
pie(table(CPS1988$parttime), col = c("green", "blue"))
table(CPS1988$parttime)
soluong = c(25631, 2524)
lamthem = c("no", "yes")
phantram = round(soluong / sum(soluong)*100, 2)
lamthem = paste(lamthem, phantram)
lamthem = paste(lamthem, "%", sep="")
pie(soluong, labels = lamthem, col=c("green", "blue"))
Biểu đồ đường
library(foreign)
test = read.dta("Table13_1.dta")
# Dữ liệu tỷ giá hối đoái (biến ex) giữa đồng USD và EURO từ mùng 4 tháng 1 năm
2000 đến mùng 8 tháng 4 năm 2008 (có 2355 quan sát)
plot(test$ex, type = "l", col = "blue", xlab = "", ylab = "Ty Gia", main = "Ty Gia Hoi Doai
USD/EUR") # Kiểu 1
par(bg = "grey90") # Đặt nền xám
plot(test$ex, type = "l", col = "blue", xlab = "", ylab = "Ty Gia", main = "Ty Gia Hoi Doai")
abline(v = c(seq(from = 1, to = 2355, by = 360)), col = "grey") # Kiểu 2
Thành phần của ggplot2
• Về cơ bản, mỗi lệnh trong gói ggplot2 có ba thành phần chủ yếu sau:
 Dữ liệu đầu vào,
 Một bộ các aesthetic mappings (kí kiệu là aes) giữa các biến số của bộ dữ liệu và các
đặc điểm hình ảnh,
 Ít nhất một layer miêu tả dữ liệu. Các layer thường được tạo ra bằng hàm geom.
• Sử dụng dữ liệu "ch4bt8.wf1"
library(ggplot2)
library(hexView)
test = readEViews("ch4bt8.wf1")
Scatter plot trong ggplot2
ggplot(test, aes(x = EDUC, y = WAGE)) + geom_point() # Cách 1
ggplot(test, aes(EDUC, WAGE)) + geom_point() # Cách 2
Scatter plot trong ggplot2
• Cho 2 nhóm lao động ứng với 2 nhóm giới tính:
test$MALE[test$MALE == 1] = "MALE"
test$MALE[test$MALE == 0] = "FEMALE"
ggplot(test, aes(EDUC, WAGE, colour = MALE)) + geom_point(show.legend = F) +
facet_wrap(~ MALE)
Scatter plot trong ggplot2
• Cho 2 nhóm lao động ứng với 2 nhóm giới tính:
ggplot(test, aes(EDUC, WAGE, colour = MALE)) + geom_point() # Gộp 2 scatter plot
Đường hồi quy trong ggplot2
• Đường hồi quy cho toàn bộ mẫu nghiên cứu với biến độc lập là WAGE còn biến phụ
thuộc là EDUC.
ggplot(test, aes(EDUC, WAGE)) + geom_point() + geom_smooth(method = "lm", se =
FALSE)
Đường hồi quy trong ggplot2
• Hai đường hồi quy ứng với 2 nhóm lao động riêng biệt và hiển thị ở cùng một biểu đồ:
ggplot(test, aes(EDUC, WAGE, colour = MALE)) + geom_point() + geom_smooth(method
= "lm")
Histogram trong ggplot2
• Histogram cho biến IQ (chỉ số thông minh IQ) riêng biệt cho hai nhóm giới tính.
ggplot(test, aes(IQ, fill = MALE)) + geom_histogram(show.legend = F) + facet_wrap(~
MALE)
Histogram trong ggplot2
• Nhạt màu một chút:
ggplot(test, aes(IQ, fill = MALE)) + geom_histogram(show.legend = F, alpha = 0.5) +
facet_wrap(~ MALE)
Box plot trong ggplot2
library(hexView)
test = readEViews("ch4bt8.wf1") # Ví dụ với dữ liệu "ch4bt8.wf1"
test$MALE[test$MALE == 1] = "MALE"
test$MALE[test$MALE == 0] = "FEMALE"
ggplot(test, aes(MALE, IQ, colour = MALE)) + geom_boxplot(show.legend = F)
# Box plot cho IQ theo hai nhóm giới tính
Hàm mật độ xác suất Density trong
ggplot2
• Vẽ hàm mật độ xác suất cho log(wage) ứng với bốn nhóm lao động đến từ 4 khu vực địa
lý:
ggplot(CPS1988, aes(log(wage), colour = region)) + geom_density() # Cách 1
Hàm mật độ xác suất Density trong
ggplot2
ggplot(CPS1988, aes(log(wage), fill = region)) + geom_density(alpha = 0.3) # Cách 2
Hàm mật độ xác suất Density trong
ggplot2
• Vẽ hàm mật độ xác suất của log(wage) với toàn bộ quan sát bằng lệnh:
ggplot(CPS1988, aes(log(wage))) + geom_density(color = "darkblue", fill = "lightblue")
Hàm mật độ xác suất Density trong
ggplot2
• Hiển thị đồng thời cả Histogram và Density:
ggplot(CPS1988, aes(log(wage))) + geom_density(alpha = 0.3, fill = "blue", color = "blue")
+ geom_histogram(aes(y = ..density..), fill = "red", color = "red", alpha = 0.3) + theme_bw()
Biểu đồ cột trong ggplot2
install.packages("tidyverse")
library(AER)
data("CPS1988")
library(tidyverse) # Vẽ số lao động theo khu vực địa lý
k1 = CPS1988 %>%group_by(region) %>% count() %>%ggplot(aes(region, n)) +
geom_col() + theme_minimal() # Kiểu 1
k1
k2 = CPS1988 %>%group_by(region) %>% count() %>%ggplot(aes(region, n, fill =
region)) + geom_col() + theme_minimal() # Kiểu 2
k2
k3 = CPS1988 %>%group_by(region) %>% count() %>%ggplot(aes(reorder(region, n), n,
fill = region)) + geom_col(show.legend = FALSE) # Kiểu 3
k3
Biểu đồ cột trong ggplot2
k4 = k3 + coord_flip() + labs(x = NULL, y = NULL, title = "Observations by Region",
caption = "Data Source: US Census Bureau") # Xoay k3 và hiệu chỉnh
k4
Biểu đồ cột trong ggplot2
k5 = CPS1988 %>% group_by(region, ethnicity) %>% count() %>%ggplot(aes(region, n)) +
geom_col() + facet_wrap(~ ethnicity, scales = "free") + geom_text(aes(label = n), color =
"white", vjust = 1.2, size = 3) + labs(x = NULL, y = NULL, title = "Observations by Region
and Ethnicity", caption = "Data Source: US Census Bureau")
# Số lao động theo khu vực địa lý và chủng tộc
k5 # Kiểu 1
k6 = CPS1988 %>% group_by(region, ethnicity) %>% count() %>%ggplot(aes(region, n, fill
= ethnicity)) + geom_col(position = "stack") + labs(x = NULL, y = NULL, title =
"Observations by Region and Ethnicity", caption = "Data Source: US Census Bureau")
# Kiểu 2
k6
k7 = CPS1988 %>% group_by(region, ethnicity) %>% count() %>%ggplot(aes(region, n, fill
= ethnicity)) + geom_col(position = "dodge") + labs(x = NULL, y = NULL, title =
"Observations by Region and Ethnicity", caption = "Data Source: US Census Bureau")
k7 # Kiểu 3
Pie chart trong ggplot2
library(dplyr)
p = CPS1988 %>% group_by(region) %>% count() %>% ggplot(aes(x = "", n, fill =
region)) + geom_col(width = 1, stat = "identity")
p # Bar chart
p + coord_polar("y", start = 0) + labs(x = NULL, y = NULL) # Pie chart
Biểu đồ đường trong ggplot2
library(foreign)
test = read.dta("Table13_1.dta")
ggplot(test, aes(time, ex)) + geom_line(col = "blue")
Biểu đồ đường trong ggplot2
library(data.table)
test = fread("cophieu.csv") # Đọc file "cophieu.csv"
library(tidyverse) # Dùng lệnh "mutate"
library(lubridate) # Định dạng lại thời gian
test %>% mutate(Date = ymd(X.DTYYYYMMDD.)) %>% ggplot(aes(Date, X.Open.)) +
geom_line(color = "blue") + facet_wrap(~ X.Ticker., drop = TRUE, scales = "free") +
theme_bw()# Kiểu 1
test %>% mutate(Date = ymd(X.DTYYYYMMDD.)) %>% ggplot(aes(Date, X.Open., color =
X.Ticker.)) + geom_line() + theme_bw() # Kiểu 2
test %>% mutate(Date = ymd(X.DTYYYYMMDD.)) %>% rename(Price = X.Open., Symbol
= X.Ticker.) %>% ggplot(aes(Date, Price, color = Symbol)) + geom_line() + theme_bw()
# Kiểu 3
Giới thiệu R commander
R commander là một session của R, cung cấp giao diện trực quan trong việc thực hiện một
số phân tích thống kê, biểu đồ, mô hình…
install.packages("Rcmdr", dependencies = TRUE)
library(Rcmdr)
Kiểm định t
Cú pháp: t.test(x1, x2) hoặc t.test(x ~ group)
library(hexView) # Ví dụ 1
test = readEViews("ch4bt8.wf1")
t.test(test$WAGE, test$EXPER)
t.test(test$IQ ~ test$MALE)
library(readxl) # Ví dụ 2
smoking = read_excel("Table8_1.xls")
t.test(smoking$educ, smoking$income)
t.test(smoking$age ~ smoking$smoker)
Kiểm định Chi-square
Cú pháp: chisq.test(data)
library(readxl)
data = read_excel("payment_food.xlsx")
library(gmodels)
head(data)
CrossTable(data$paid_last_month, data$worried_food)
data2 = matrix(c(394, 1014, 50, 73, 47, 35), nrow = 3, byrow = T) # Tạo file dữ liệu
data2
chisq.test(data2) # Kiểm định chi-square
Phân tích phương sai một chiều (1)
library(hexView)
test = readEViews("ch4bt8.wf1", as.data.frame = TRUE)
anova1 = lm(WAGE ~ BLACK, data = test) # Một biến phân nhóm
summary(anova1)
t.test(test$WAGE ~ test$BLACK)
boxplot(test$WAGE ~ test$BLACK)
anova2 = lm(WAGE ~ BLACK + SOUTH, data = test) # Hai biến phân nhóm
summary(anova2)
anova3 = lm(WAGE ~ BLACK + SOUTH + BLACK*SOUTH, data = test) # Biến tương
tác
summary(anova3)
Phân tích phương sai một chiều (2)
ancova1 = lm(WAGE ~ URBAN + EDUC, data = test)
# Gồm biến phân nhóm và định lượng
summary(ancova1)
ancova2 = lm(WAGE ~ URBAN + EDUC + URBAN*EDUC, data = test)
# Thêm biến tương tác
summary(ancova2)
Hồi quy đơn
library(hexView)
test = readEViews("ch2_health.wf1", as.data.frame = TRUE)
hoiquy = lm(HEALTH ~ INCOME, data = test) # Hồi quy đơn
summary(hoiquy) # Kết quả hồi quy
library(ggplot2)
ggplot(test, aes(INCOME, HEALTH)) + geom_point() + geom_smooth(method = "lm")
# Đường hồi quy với khoảng tin cậy 95%
hoiquybac2 = lm(HEALTH ~ I(INCOME^2), data = test) # Hồi quy bậc 2
hoiquykhonghesochan = lm(HEALTH ~ 0 + INCOME, data = test)
# Hồi quy không hệ số chặn
Hồi quy đơn
Thông tin từ hồi quy đơn
Tên hàm Chức năng
print() Hiển thị kết quả hồi quy ở dạng đơn giản
summary() Hiển thị kết quả hồi quy ở dạng chi tiết
coef() Hiện thị các hệ số hồi quy trong mô hình
residuals() Hiển thị phần dư
fitted() Hiển thị giá trị ước lượng (fitted values)
anova() Hiển thị bảng ANOVA
predict() Dự đoán
Hiển thị khoảng tin cậy (mặc định 95%) cho các hệ số hồi quy. Nếu khoảng tin
confint()
cậy 90%, thì thêm level = 0.9
deviance() Hiển thị tổng bình phương phần dư (RSS)
vcov() Hiển thị ma trận variance-covariance
df.residual() Hiển thị giá trị n - k (bậc tự do của mô hình hồi quy)
logLik() Hiển thị giá trị Log-likelihood
plot() Hiển thị 4 graphs tiêu chuẩn dùng để tìm các quan sát bất thường
deviance() Tính tổng bình phương phần dư
Hồi quy tuyến tính (LPM)
library(readxl)
test = read_excel("Table1_1.xls")
head(test)
ols1 = lm(wage ~ female + nonwhite + union + education + exper, data = test)
# Hồi quy
summary(ols1) # Kết quả hồi quy
anova(ols1) # Phân tích phương sai
plot(wage ~ education, data = test, col = "blue") # Đường hồi quy (cách 1)
abline(lm(wage ~ education, data = test), col = "red")
ggplot(test, aes(education, wage)) + geom_point() + geom_smooth(method = "lm")
# Đường hồi quy giữa education và wage (cách 2)
Hồi quy tuyến tính (LPM)
install.packages("jtools", dependencies = TRUE)
install.packages("officer")
install.packages("flextable") # Cài đặt các gói jtools, officer, và flextable
library(jtools)
library(officer)
library(flextable)
set_summ_defaults(digits = 3, model.info = TRUE, model.fit = TRUE, confint = TRUE, vifs
= TRUE, pvals = TRUE, robust = TRUE) # Đặt các giá trị mặc định cho hàm summ
summ(ols1) # Kết quả hồi quy
export_summs(ols1, robust = TRUE, to.file = "docx", file.name = "test.docx")
# Xuất kết quả hồi quy thành file Word
Ý nghĩa p-value
• Giả thuyết H1: B tác động đến A
• Giả thuyết H0: B không tác động đến A
• Tiến hành thu thập dữ liệu (D)
• p-value = 0.05 có nghĩa là gì?
• p-value = 0.05 hay Pr(D | H0) = 0.05
hay xác suất tìm được dữ liệu D để H0 đúng (thỏa mãn H0) là 5%
• p-value <= 0.1  bác bỏ H0, chấp nhận H1

Pr(D | H0) ≠ Pr(H0 | D)


Kiểm định phân phối của phần dư
library(dplyr)
test = test %>% mutate(phandu = ols1$residuals)
summary(test$phandu)
library(ggplot2)
theme_set(theme_minimal())
test %>% ggplot(aes(phandu)) + geom_density(alpha = 0.3, fill = "blue", color = "blue") +
geom_histogram(aes(y = ..density..), fill = "red", color = "red", alpha = 0.3)
library(fBasics)
jarqueberaTest(test$phandu)
Kiểm định Durbin - Watson
library(lmtest)
ols1 %>% dwtest()
Kiểm định Wald cho hệ số hồi quy
library(AER) # Dùng gói AER
ols1 = lm(wage ~ female + nonwhite + union + education + exper, data = test)
summary(ols1)
linearHypothesis(ols1, "education = 0.2")
# Kiểm định hệ số hồi quy của education bằng 0.2
linearHypothesis(ols1, c("(Intercept) = 70", "education = 0.2", "exper = 1.6"))
# Kiểm định nhiều hệ số hồi quy
Hồi quy hai biến qua gốc tọa độ
library(readxl)
test = read_excel("table6_1.xls")
head(test)
ols1 = lm(Y ~ 0 + X, data = test) # Hồi quy với hệ số chặn = 0
summary(ols1)
ols2 = lm(Y ~ X, data = test) # Hồi quy với hệ số chặn không chắc chắn
summary(ols2)
Mô hình hồi quy phổ biến
• Mô hình logarit tuyến tính (log-linear model)
• Mô hình bán logarit (semilog model)
• Mô hình tuyến tính – logarit (lin – log model)
• Mô hình nghịch đảo (reciprocal model)
• Mô hình đa thức (polyniminal model)
Mô hình logarit tuyến tính (log-linear
model)
Dạng hàm:
Hàm sản xuất (unrestricted regression):
Restricted regression:
test = read_excel("Table2_1.xls")
logatt = lm(log(output) ~ log(labor) + log(capital), data = test)
summary(logatt) # Mô hình logarit t.tính
logatt2 = lm(log(output / labor) ~ log(capital / labor), data = test) # Mô hình bị giới hạn
summary(logatt2)
Mô hình bán logarit (semilog model)
Dạng hàm:
test = read_excel("Table2_5.xls")
semilog = lm(log(rgdp) ~ time, data = test) # Hồi quy
summary(semilog)
library(ggplot2)
ggplot(test, aes(time, log(rgdp))) + geom_line() + geom_point(col = "red")
# Minh họa
Mô hình tuyến tính - logarit (lin - log
model)
Dạng hàm:
test = read_excel("TienLuong(Chuong3).xls")
test$LKN = log(test$KinhNghiem) # Tạo biến log(KinhNghiem)
summary(lm(TienLuong ~ LKN, data = test)) # Kết quả hồi quy
ggplot(test, aes(LKN, TienLuong)) + geom_point() + geom_smooth(method = "lm")
# Đường hồi quy
Mô hình nghịch đảo (reciprocal model)
Dạng hàm:
library(readxl)
test = read_excel("Table2_8.xls")
summary(lm(sfdho ~ I(expend^-1), data = test)) # Hồi quy
library(dplyr) # Gọi gói "dplyr"
test %>% ggplot(aes(x = expend, y = sfdho)) + geom_point(alpha = 0.3) +
geom_smooth(formula = y ~ 1/x, method = "loess") # Minh họa
Mô hình đa thức (polyniminal model)
Dạng hàm:
library(readxl)
test = read_excel("gdp.xls")
summary(lm(R_GDP ~ Tgian + I(Tgian^2), data = test)) # Hồi quy
Mô hình hồi quy bội
library(hexView)
test = readEViews("ch2vd5.WF1", as.data.frame = TRUE)
hoiquyboi = lm(CT ~ TN + TS, data = test) # Hồi quy
summary(hoiquyboi) # Kết quả hồi quy
confint(hoiquyboi)
confint(hoiquyboi, level = 0.99)
Multicollinearity (1)
X2 X3 X4
10 50 52
15 75 75
18 90 97
24 120 129
30 150 152

dct = data.frame(x2 = c(10, 15, 18, 24, 30), x3 = c(50, 75, 90, 120, 150), x4 = c(52, 75, 97,
129, 152)) # Nhập liệu
cor(dct) # Tương quan biến số
• X3=5X2 (cộng tuyến hoàn hảo – perfect collinearity) hay tương quan giữa X3 và X2 bằng 1.
• Tương quan gữa X3 và X4 gần bằng 1 (cộng tuyến phi hoàn hảo - imperfect collinearity hay
near collinearity).
Multicollinearity (2)
library(readxl)
test = read_excel("Table4_4.xls")
multi = lm(hours ~ age + educ + exper + faminc + fathereduc + hage + heduc + hhours +
hwage + kidsl6 + kids618 + wage + mothereduc + mtr + unemployment, data = test)
summary(multi)
library(car) # Gọi gói car
vif(multi) # Tính VIF (variance inflation factor)
multi2 = lm(hours ~ age + educ + exper + faminc + hhours + hwage + kidsl6 + wage +mtr +
unemployment, data = test) # Loại bớt biến
vif(multi2) # Tính lại VIF
Multicollinearity (3)
test2 = select(test, age, educ, exper, faminc, fathereduc, hage, heduc, hhours, hwage, kidsl6,
kids618, wage, mothereduc, mtr, unemployment) # Phương pháp PCA
test2.pca = prcomp(test2, center = TRUE, scale. = TRUE)
summary(test2.pca)
plot(test2.pca) # Vẽ biểu đồ PCA
install.packages("devtools")
install_github("vqv/ggbiplot")
library(devtools)
library(ggbiplot)
ggbiplot(test2.pca)
ggbiplot(test2.pca, labels=rownames(test2))
Heteroskedasticity (1)
• Homoskedasticity >< Heteroskedasticity
với
library(readxl)
test = read_excel("Table5_1.xls")
homo = lm(abortion ~ religion + price + laws + funds + educ + income + picket, data = test)
summary(homo) # Kết quả hồi quy
test$resquare = residuals(homo)^2 # Phần dư bình phương
test$abortionf = predict(homo) # Fitted value
hist(test$resquare) # Histogram của phần dư b.p
plot(test$resquare ~ test$abortionf) # Phần dư b.p và fitted value
Heteroskedasticity (2)
• Kiểm định Park
• Kiểm định Glejser
• Kiểm định Goldfeld - Quandt
• Kiểm định Breusch - Pagan
• Kiểm định White
• Kiểm định Koenker - Basett
Kiểm định Breusch - Pagan
homo = lm(abortion ~ religion + price + laws + funds + educ + income + picket, data = test)
summary(homo)
test$resquare = residuals(homo)^2
bptest = lm(resquare ~ religion + price + laws + funds + educ + income + picket, data=test)
summary(bptest)

Interpretation: Hệ số hồi quy của mô hình cho residual squared khác 0 


Heteroskedasticity
Kiểm định White
test$abortionf = predict(homo)
test$abortionf2 = test$abortionf^2
wtest = lm(resquare ~ abortionf + abortionf2, data=test)
summary(wtest)

Interpretation: F-statistic có ý nghĩa thống kê  Heteroskedasticity


Autocorrelation
library(readxl)
test = read_excel("Table6_1.xls")
summary(auto)
auto = lm(lnconsump ~ lndpi + lnwealth + interest, data = test)
library(jtools)
summ(auto)
library(lmtest)
bgtest(lnconsump ~ lndpi + lnwealth + interest, order = 2, data = test)
# Breusch-Godfrey test
Model Specification Errors
• Omission of relevant variables
• Inclusion of irrelevant or unnecessary variables
• Misspecification of the functional form of a regression model
• Outliers, leverage and influence data
Kiểm định Wald
mse1 = lm(wage ~ female + nonwhite + union + education + exper, data = test)
summary(mse1)
mse2 = lm(wage ~ female + nonwhite + union + education + exper + I(exper^2), data=test)
summary(mse2)
library(AER)
linearHypothesis(mse2, "I(exper^2) = 0") # Cách 1
anova(mse2, mse1) # Cách 2: Kiểm định F

 Mô hình bỏ sót biến


Ramsey’s RESET test
library(lmtest) # Cách 1
resettest(mse1, power = 2:3, type = c("regressor"), data = test)
test$fit = predict(mse1) # Cách 2
ramsey = lm(data = test, wage ~ female + nonwhite + union + education + exper + I(fit^2) +
I(fit^3))
summary(ramsey)
anova(ramsey, mse1)
Lagrange Multiplier test
test$resids = residuals(mse1)
lmt = lm(data = test, resids ~ female + nonwhite + union + education + exper + I(exper^2))
summary(lmt)
qchisq(0.95, 1)
Inclusion of irrelevant or unnecessary
variables
mse3 = lm(wage ~ female + nonwhite + union + education + exper + age, data = test)
# Thêm biến age
summary(mse3)
mse4 = lm(wage ~ age, data = test)
summary(mse4)
Misspecification of the functional form of a
regression model
mse5 = lm(wage ~ female + nonwhite + union + education + exper + I(exper^2) +
I(exper*female), data = test)
summ(mse5)
mse6 = lm(log(wage) ~ female + nonwhite + union + education + exper + I(exper^2) +
I(exper*female), data = test)
summ(mse6)
a = deviance(mse5)
b = deviance(mse6)
1289/2*log(a/b)
Outliers, leverage and influence data
install.packages("ggfortify")
library(ggfortify)
autoplot(ols1, which = 1:4, ncol = 2, label.size = 3) # Phát hiện outliers
library(MASS)
robustHuber = rlm(wage ~ female + nonwhite + union + education + exper, data = test)
summary(robustHuber)
ols2 = lm(wage ~ female + nonwhite + union + education + exper, data = test[-c(716, 796,
1071), ]) # Loại các quan sát
summary(ols2)
Linear probability model (LPM)
• Smoker = 1 for smokers and 0 for nonsmokers
• Age = age in years
• Education = number of years of schooling
• Income = family income
• Pcigs = price of cigarettes in individual states in 1979

Yi = B1 + B2Agei + B3Educi + B4Incomei + B5Pcigs + ui


Linear probability model (LPM)
• Sử dụng lệnh:
library(readxl) # Gọi gói "readxl"
smoking = read_xls("Table8_1.xls") # Đọc file "Table8_1.xls"
lpm = lm(smoker ~ age + educ + income + pcigs79, data = smoking)
# Chạy hồi quy
summary(lpm) # Xem kết quả hồi quy
Linear probability model (LPM)
Tuy nhiên, mô hình LPM trên có một số nhược điểm:
1) LPM cho rằng xác xuất quan sát thấy hành vi hút thuốc là quan hệ tuyến tính với các
biến giải thích bất kể quy mô về giá trị của các biến số này.
2) Xác suất của một sự kiện phải nằm giữa 0 và 1 nhưng LPM không đảm bảo rằng các giá
trị xác suất ước lượng sẽ nằm trong khoảng này.
3) Giả định về sai số ngẫu nhiên tuân theo phân phối chuẩn có thể không còn đúng nữa khi
biến phụ thuộc chỉ nhận một trong hai giá trị 0 và 1.
4) Phương sai của sai số ngẫu nhiên là thay đổi, làm cho các kiểm định truyền thống là
không đáng tin.
Logit model (1)
• Sử dụng lệnh:
library(readxl) # Gọi gói "readxl"
smoking = read_xls("Table8_1.xls") # Đọc file "Table8_1.xls"
logit = glm(smoker ~ age + educ + income + pcigs79, family = binomial, data = smoking)
# Chạy hồi quy
summary(logit) # Xem kết quả hồi quy
1
𝑃 𝑖= −𝑍
1 +𝑒 𝑖

where: = probability of smoking, and

Ví dụ: Tính xác suất hút thuốc và không hút thuốc của người có age = 28, educ = 15,
income = 12,500, và pcigs79 = 60.0?
Marginal effects in logit model
• Marginal effect = The effect of a unit change in the mean value of the explanatory
variables on the probability of smoking.
install.packages("margins") # Cài gói "margins"
library(margins) # Gọi gói "margins"
m = margins(logit) # Tính marginal effects của logit model
summary(m) # Xem kết quả marginal effects
margins_summary(logit) # Một cách khác để xem kết quả marginal effects
plot(m) # Vẽ biểu đồ
summary(margins(logit, variables = "age")) # Marginal effects của một biến số
margins(logit, at = list(smoker = 0:1)) # Marginal effects tại một giá trị cụ thể
Odds ratio (OR) in logit model
install.packages("questionr") # Cài gói "questionr"
library(questionr) # Gọi gói "questionr"
odd.ratio(logit) # Cách 1
odds.ratio(logit, level = 0.95) # Cách 2
x = summary(logit) # Gán kết quả mô hình vào object "x"
sink("x.txt") # Tạo file "x.txt" chứa kết quả hồi quy
print(x) # Đưa kết quả hồi quy vào file "x.txt"
Probit model
• Distribution of the error term:
• The LPM: non-normal distribution.
• The logit model: logistic distribution.
• The probit model: normal distribution.
probit = glm(smoker ~ age + educ + income + pcigs79, family = binomial(link =
"probit"), data = smoking) # Chạy mô hình probit
probit2 = glm(smoker ~ age + educ + income + pcigs79 + educincome, family =
binomial(link = "probit"), data = smoking) # Thêm biến tương tác
summary(probit) # Xem kết quả mô hình 1
summary(probit2) # Xem kết quả mô hình 2
Multinomial regression models (MRM)
• Choosing among several discrete alternatives  multinomial regression models
(MRM)
• Nominal MRM for chooser or individual-specific data
Multinomial logit (MLM) or
Multinomial probit models (MPM)
• Nominal MRM for choice-specific data
Conditional logit (CLM) or
Conditional probit (CPM) models
• Mixed MRM
Mixed logit model
Multinomial logit model (MLM): school
choice
X2 = hscath = 1 if Catholic school graduate, 0 otherwise
X3 = grades = average grade in math, English, and social studies on a 13 point grading
scale, with 1 for the highest grade and 13 for the lowest grade. Therefore, higher grade-scale
denotes poor academic performance
X4 = faminc = gross family income in 1991 in thousands of dollars
X5 = famsiz =number of family members
X6 = parcoll= 1 if the most educated parent graduated from college or had an advanced
degree
X7 = 1 if female
X8 = 1 if black
Multinomial logit model (MLM): school
choice
library(readxl)
school = read_excel("Table9_1.xls")
str(school)
install.packages("nnet") # Cài gói "nnet"
library(nnet) # Gọi gói "nnet"
school$psechoice = relevel(school$psechoice, ref="1") # Xác định reference category
s = multinom(psechoice ~ ., data = school) # Chạy mô hình với tất cả biến số
s2 = multinom(psechoice ~ . -hscath, data = school) # Chạy mô hình không có "hscath"
summary(s) # Xem kết quả
Multinomial logit model (MLM): school
choice
z = summary(s)$coefficients/summary(s)$standard.errors
p = (1 - pnorm(abs(z), 0, 1))*2 # Tính p=value
p # Xem kết quả p-value
Conditional logit model (CLM): travel
mode
Mode = Choice: air, train, bus or car
Time = Terminal waiting time, 0 for car
Invc = In-vehicle cost–cost component
Invt = Travel time in vehicle
GC = Generalized cost measure13
Hinc = Household income
Psize = Party size in mode chosen
Conditional logit model (CLM): travel
mode
library(readxl)
travel = read_excel("Table9_3.xls")
str(travel)
library(survival) # Gọi gói "survival"
t = clogit(choice ~ termtime + invehiclecost + traveltime + travelcost + air + train + bus +
strata(id), data = travel) # Chạy mô hình
summary(t) # Xem kết quả

• Interpretation: For any mode of transportation, holding the other modes constant,
increasing the terminal time by 1 minute decreases the odds of that mode by about 10%.
Mixed logit (MXL)
library(readxl)
travel = read_excel("Table9_3.xls")
str(travel)
x = c(air*inc, train*inc, bus*inc, air*psize, train*psize, and bus*psize)
library(survival) # Gọi gói "survival"
mix = clogit(choice ~ termtime + invehiclecost + traveltime + air + train + bus + x +
strata(id), data = travel) # Chạy mô hình
summary(mix) # Xem kết quả

• Interpretation: A unit increase in family income, decreases the odds of traveling by train
by about 5.75% [(1 – 0.94250) × 100], holding all else constant.
Ordered multinomial models (OMM)
• Response categories are ordered or ranked
• apply = 1: unlikely,
• apply = 2: somewhat likely,
• apply = 3: very likely to apply to graduate school.
• pared = 1: at least one parent has graduate education
• public = 1: the undergraduate institution is a public university
• GPA: student’s grade point average
Ordered multinomial models (OMM)
library(readxl)
grad = read_excel("Table10_4_data.xls")
str(grad)
install.packages("MASS") # Cài đặt gói "MASS"
library(MASS) # Gọi gói "MASS"
grad$apply = factor(grad$apply) # Chuyển biến apply thành dạng factor
ologit = polr(apply ~ pared + public + gpa, data = grad, Hess = TRUE) # Chạy mô hình
summary(ologit) # Xem kết quả
exp(coef(ologit)) # Tính odd ratio
• Interpretation: The OR of pared of 0.77 suggests that if we increase pared by 1 unit (i.e.
going from 0 to 1), the odds of high apply vs. the combined middle and low apply are
0.77 times greater than if neither parent went to college, ceteris paribus.
Poisson Regression Models (PRM)
library(readxl)
pat = read_excel("Table12_1.xls")
str(pat)
p = glm(p90 ~ . -p91 -lr91, family="poisson", data=pat) # Chạy mô hình
summary(p) # Xem kết quả

• Interpretation 1: The LR90 coefficient of 0.86 suggests that if R&D expenditure


increases by 1%, the average number of patents given a firm will increase by about
0.86%. (Note that R&D expenditure is expressed in logarithmic form.)
• Interpretation 2: The coefficient of the US dummy of -0.4189 means the average
number of patents in the USA is lower by 100[e-0.4189 - 1] = 100(0.6577 - 1) = -34.23%
compared to the base group.
Trân trọng cảm ơn các bạn.

You might also like