R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot. Ngày 2: Hiển thị dữ liệu # Việc 1. Đọc dữ liệu “CHNS data full.csv” vào R và gọi dữ liệu là “df”

df = read.csv("D:\\NGHIEN CUU KHOA HOC\\15. R\\CHNS data full.csv")

Hiển thị 6 dòng đầu

head(df)
##   id whours wgroup dead fu.time gender age edu marital residence income occu
## 1  1     35      1    0       4      2  52   3       3         1 116000    1
## 2  2     48      3    0       4      1  36   3       2         1  25200    1
## 3  3     40      1    0       4      2  31   3       2         1  27000    1
## 4  4     48      3    0       4      2  51   2       2         1  27600    2
## 5  5     32      2    0       4      1  58   2       2         1  34800    2
## 6  6     40      1    0       4      1  42   3       2         1  77000    1
##   smoking drinking height weight   bmi sys1 sys2 sys3 dias1 dias2 dias3 tsf1
## 1       0        0    168   83.5 29.58  120  126  120    80    82    76   28
## 2       1        0    173   85.0 28.40  120  120  120    90    80    80   25
## 3       0        1    167   50.0 17.93  110  108  110    70    70    70   18
## 4       0        0    164   80.0 29.74  120  110  120    80    82    80   27
## 5       0        0    175   65.0 21.22  120  120  120    80    82    80   23
## 6       0        1    179   75.0 23.41  110  112  110    72    76    70   24
##   tsf2 tsf3 uac  hc  wc
## 1   27   28  36 111 103
## 2   44   25  35 102  95
## 3   17   18  25  96  72
## 4   26   27  32 104  97
## 5   22   22  35 102  90
## 6   23   24  28  96  90

Việc 2: Soạn biểu đồ phân bố histogram

2.1 Thể hiện phân bố thu nhập (income) bằng biểu đồ histogram

library(ggplot2)
library(gridExtra) 
## Warning: package 'gridExtra' was built under R version 4.3.3
p = ggplot(data = df, aes(x = income))
p1 = p + geom_histogram()
p2 = p + geom_histogram(fill = "blue", col = "white") + labs(x = "Thu nhập", y = "Số người", title = "Phân bố thu nhập")

grid.arrange(p1, p2, ncol = 2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 224 rows containing non-finite outside the scale range
## (`stat_bin()`).
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 224 rows containing non-finite outside the scale range
## (`stat_bin()`).

## Nhận xét: Phân bố lệch, không rõ ràng. ## 2.2 Thể hiện phân bố thu nhập (income) rõ ràng hơn bằng biểu đồ histogram:

p = ggplot(data = df, aes(x = log(income)))
p1 = p + geom_histogram(fill = "blue", col = "white") + labs(x = "Thu nhập (logarithm scale)", y = "Số người", title = "Phân bố thu nhập")
p1 
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_bin()`).

## 2.3 Hãy vẽ biểu đồ phân bố thu nhập (income) theo giới tính (gender):

p = ggplot(data = df, aes(x = log(income), fill = factor(gender)))
p1 = p + geom_histogram(col="white") + labs(x = "Thu nhập (logarithm scale)", y = "Số người", title = "Phân bố thu nhập")
p2 = p + geom_density(alpha = 0.5) + labs(x = "Thu nhập (logarithm scale)", y = "Tỉ lệ", title = "Phân bố thu nhập")

grid.arrange(p1, p2, ncol = 2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_bin()`).
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_density()`).

# Việc 3: Soạn biểu đồ thanh thể hiện thu nhập (income) theo trình độ học vấn (edu) ## 3.1 Thể hiện thu nhập (income) theo trình độ học vấn (edu) ## Gọi lệnh đếm

library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.3
## Warning: package 'tibble' was built under R version 4.3.3
## Warning: package 'tidyr' was built under R version 4.3.3
## Warning: package 'readr' was built under R version 4.3.3
## Warning: package 'purrr' was built under R version 4.3.3
## Warning: package 'dplyr' was built under R version 4.3.3
## Warning: package 'stringr' was built under R version 4.3.3
## Warning: package 'forcats' was built under R version 4.3.3
## Warning: package 'lubridate' was built under R version 4.3.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.4     ✔ tibble    3.2.1
## ✔ purrr     1.0.4     ✔ tidyr     1.3.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::combine() masks gridExtra::combine()
## ✖ dplyr::filter()  masks stats::filter()
## ✖ dplyr::lag()     masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Vẽ biểu đồ hình thanh

library(tidyverse)

Đặt tên file mới temp

temp = df %>% group_by(edu) %>% summarise(income = median(income, na.rm = T))
temp
## # A tibble: 3 × 2
##     edu income
##   <int>  <dbl>
## 1     1  1750.
## 2     2  6420 
## 3     3 31200

Vẽ biểu đồ thanh

df$edu = as.character(factor(df$edu, levels = c(1, 2, 3), labels = c("Primary", "Secondary", "Tertary")))
p = ggplot(data = temp, aes(x = edu, y = income, fill = edu))
p1 = p + geom_bar(stat = "identity") + labs(x = "Education", y = "Income") + theme(legend.position = "none")
p1

3.2 Thêm giá trị thu nhập vào biểu đồ

p + geom_bar(stat = "identity") + geom_text(aes(label = income, vjust = -0.5)) + geom_bar(stat = "identity") + labs(x = "Education", y = "Income") + theme(legend.position="none")

Việc 4: Soạn biểu đồ hộp so sánh phân bố của thu nhập theo giới tính

df$gender = as.character(factor(df$gender, levels = c(1, 2), labels = c("Men", "Women")))
p = ggplot(data = df, aes(x = factor(gender), y = log(income), col = factor(gender)))
p + geom_boxplot() + geom_jitter(alpha = 0.05) + labs(x = "Giới tính", y = "Thu nhập (logarithm scale)") + ggtitle("Thu nhập theo giới tính")
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 224 rows containing missing values or values outside the scale range
## (`geom_point()`).