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.

# Nạp gói NHANES
library(NHANES)

# Xem dữ liệu
data(NHANES)

# Số dòng và số cột
dim(NHANES)
## [1] 10000    76
# 10 dòng đầu tiên
head(NHANES, 10)
##       ID SurveyYr Gender Age AgeDecade AgeMonths Race1 Race3    Education
## 1  51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 2  51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 3  51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 4  51625  2009_10   male   4       0-9        49 Other  <NA>         <NA>
## 5  51630  2009_10 female  49     40-49       596 White  <NA> Some College
## 6  51638  2009_10   male   9       0-9       115 White  <NA>         <NA>
## 7  51646  2009_10   male   8       0-9       101 White  <NA>         <NA>
## 8  51647  2009_10 female  45     40-49       541 White  <NA> College Grad
## 9  51647  2009_10 female  45     40-49       541 White  <NA> College Grad
## 10 51647  2009_10 female  45     40-49       541 White  <NA> College Grad
##    MaritalStatus    HHIncome HHIncomeMid Poverty HomeRooms HomeOwn       Work
## 1        Married 25000-34999       30000    1.36         6     Own NotWorking
## 2        Married 25000-34999       30000    1.36         6     Own NotWorking
## 3        Married 25000-34999       30000    1.36         6     Own NotWorking
## 4           <NA> 20000-24999       22500    1.07         9     Own       <NA>
## 5    LivePartner 35000-44999       40000    1.91         5    Rent NotWorking
## 6           <NA> 75000-99999       87500    1.84         6    Rent       <NA>
## 7           <NA> 55000-64999       60000    2.33         7     Own       <NA>
## 8        Married 75000-99999       87500    5.00         6     Own    Working
## 9        Married 75000-99999       87500    5.00         6     Own    Working
## 10       Married 75000-99999       87500    5.00         6     Own    Working
##    Weight Length HeadCirc Height   BMI BMICatUnder20yrs      BMI_WHO Pulse
## 1    87.4     NA       NA  164.7 32.22             <NA>    30.0_plus    70
## 2    87.4     NA       NA  164.7 32.22             <NA>    30.0_plus    70
## 3    87.4     NA       NA  164.7 32.22             <NA>    30.0_plus    70
## 4    17.0     NA       NA  105.4 15.30             <NA>    12.0_18.5    NA
## 5    86.7     NA       NA  168.4 30.57             <NA>    30.0_plus    86
## 6    29.8     NA       NA  133.1 16.82             <NA>    12.0_18.5    82
## 7    35.2     NA       NA  130.6 20.64             <NA> 18.5_to_24.9    72
## 8    75.7     NA       NA  166.7 27.24             <NA> 25.0_to_29.9    62
## 9    75.7     NA       NA  166.7 27.24             <NA> 25.0_to_29.9    62
## 10   75.7     NA       NA  166.7 27.24             <NA> 25.0_to_29.9    62
##    BPSysAve BPDiaAve BPSys1 BPDia1 BPSys2 BPDia2 BPSys3 BPDia3 Testosterone
## 1       113       85    114     88    114     88    112     82           NA
## 2       113       85    114     88    114     88    112     82           NA
## 3       113       85    114     88    114     88    112     82           NA
## 4        NA       NA     NA     NA     NA     NA     NA     NA           NA
## 5       112       75    118     82    108     74    116     76           NA
## 6        86       47     84     50     84     50     88     44           NA
## 7       107       37    114     46    108     36    106     38           NA
## 8       118       64    106     62    118     68    118     60           NA
## 9       118       64    106     62    118     68    118     60           NA
## 10      118       64    106     62    118     68    118     60           NA
##    DirectChol TotChol UrineVol1 UrineFlow1 UrineVol2 UrineFlow2 Diabetes
## 1        1.29    3.49       352         NA        NA         NA       No
## 2        1.29    3.49       352         NA        NA         NA       No
## 3        1.29    3.49       352         NA        NA         NA       No
## 4          NA      NA        NA         NA        NA         NA       No
## 5        1.16    6.70        77      0.094        NA         NA       No
## 6        1.34    4.86       123      1.538        NA         NA       No
## 7        1.55    4.09       238      1.322        NA         NA       No
## 8        2.12    5.82       106      1.116        NA         NA       No
## 9        2.12    5.82       106      1.116        NA         NA       No
## 10       2.12    5.82       106      1.116        NA         NA       No
##    DiabetesAge HealthGen DaysPhysHlthBad DaysMentHlthBad LittleInterest
## 1           NA      Good               0              15           Most
## 2           NA      Good               0              15           Most
## 3           NA      Good               0              15           Most
## 4           NA      <NA>              NA              NA           <NA>
## 5           NA      Good               0              10        Several
## 6           NA      <NA>              NA              NA           <NA>
## 7           NA      <NA>              NA              NA           <NA>
## 8           NA     Vgood               0               3           None
## 9           NA     Vgood               0               3           None
## 10          NA     Vgood               0               3           None
##    Depressed nPregnancies nBabies Age1stBaby SleepHrsNight SleepTrouble
## 1    Several           NA      NA         NA             4          Yes
## 2    Several           NA      NA         NA             4          Yes
## 3    Several           NA      NA         NA             4          Yes
## 4       <NA>           NA      NA         NA            NA         <NA>
## 5    Several            2       2         27             8          Yes
## 6       <NA>           NA      NA         NA            NA         <NA>
## 7       <NA>           NA      NA         NA            NA         <NA>
## 8       None            1      NA         NA             8           No
## 9       None            1      NA         NA             8           No
## 10      None            1      NA         NA             8           No
##    PhysActive PhysActiveDays TVHrsDay CompHrsDay TVHrsDayChild CompHrsDayChild
## 1          No             NA     <NA>       <NA>            NA              NA
## 2          No             NA     <NA>       <NA>            NA              NA
## 3          No             NA     <NA>       <NA>            NA              NA
## 4        <NA>             NA     <NA>       <NA>             4               1
## 5          No             NA     <NA>       <NA>            NA              NA
## 6        <NA>             NA     <NA>       <NA>             5               0
## 7        <NA>             NA     <NA>       <NA>             1               6
## 8         Yes              5     <NA>       <NA>            NA              NA
## 9         Yes              5     <NA>       <NA>            NA              NA
## 10        Yes              5     <NA>       <NA>            NA              NA
##    Alcohol12PlusYr AlcoholDay AlcoholYear SmokeNow Smoke100  Smoke100n SmokeAge
## 1              Yes         NA           0       No      Yes     Smoker       18
## 2              Yes         NA           0       No      Yes     Smoker       18
## 3              Yes         NA           0       No      Yes     Smoker       18
## 4             <NA>         NA          NA     <NA>     <NA>       <NA>       NA
## 5              Yes          2          20      Yes      Yes     Smoker       38
## 6             <NA>         NA          NA     <NA>     <NA>       <NA>       NA
## 7             <NA>         NA          NA     <NA>     <NA>       <NA>       NA
## 8              Yes          3          52     <NA>       No Non-Smoker       NA
## 9              Yes          3          52     <NA>       No Non-Smoker       NA
## 10             Yes          3          52     <NA>       No Non-Smoker       NA
##    Marijuana AgeFirstMarij RegularMarij AgeRegMarij HardDrugs SexEver SexAge
## 1        Yes            17           No          NA       Yes     Yes     16
## 2        Yes            17           No          NA       Yes     Yes     16
## 3        Yes            17           No          NA       Yes     Yes     16
## 4       <NA>            NA         <NA>          NA      <NA>    <NA>     NA
## 5        Yes            18           No          NA       Yes     Yes     12
## 6       <NA>            NA         <NA>          NA      <NA>    <NA>     NA
## 7       <NA>            NA         <NA>          NA      <NA>    <NA>     NA
## 8        Yes            13           No          NA        No     Yes     13
## 9        Yes            13           No          NA        No     Yes     13
## 10       Yes            13           No          NA        No     Yes     13
##    SexNumPartnLife SexNumPartYear SameSex SexOrientation PregnantNow
## 1                8              1      No   Heterosexual        <NA>
## 2                8              1      No   Heterosexual        <NA>
## 3                8              1      No   Heterosexual        <NA>
## 4               NA             NA    <NA>           <NA>        <NA>
## 5               10              1     Yes   Heterosexual        <NA>
## 6               NA             NA    <NA>           <NA>        <NA>
## 7               NA             NA    <NA>           <NA>        <NA>
## 8               20              0     Yes       Bisexual        <NA>
## 9               20              0     Yes       Bisexual        <NA>
## 10              20              0     Yes       Bisexual        <NA>
library(NHANES)

df <- NHANES[, c("Age", "Gender", "Race1", "Education", 
                 "BMI", "BMI_WHO", "HHIncomeMid", "Poverty")]

# Kiểm tra
dim(df)
## [1] 10000     8
head(df, 10)
##    Age Gender Race1    Education   BMI      BMI_WHO HHIncomeMid Poverty
## 1   34   male White  High School 32.22    30.0_plus       30000    1.36
## 2   34   male White  High School 32.22    30.0_plus       30000    1.36
## 3   34   male White  High School 32.22    30.0_plus       30000    1.36
## 4    4   male Other         <NA> 15.30    12.0_18.5       22500    1.07
## 5   49 female White Some College 30.57    30.0_plus       40000    1.91
## 6    9   male White         <NA> 16.82    12.0_18.5       87500    1.84
## 7    8   male White         <NA> 20.64 18.5_to_24.9       60000    2.33
## 8   45 female White College Grad 27.24 25.0_to_29.9       87500    5.00
## 9   45 female White College Grad 27.24 25.0_to_29.9       87500    5.00
## 10  45 female White College Grad 27.24 25.0_to_29.9       87500    5.00
names(df)
## [1] "Age"         "Gender"      "Race1"       "Education"   "BMI"        
## [6] "BMI_WHO"     "HHIncomeMid" "Poverty"
library(ggplot2)

# 1. Histogram thông thường
ggplot(df, aes(x = HHIncomeMid)) +
  geom_histogram(bins = 30, fill = "steelblue", color = "white", alpha = 0.8) +
  labs(
    title = "Phân bố thu nhập hộ gia đình (HHIncomeMid)",
    x = "Household Income Midpoint",
    y = "Số lượng"
  ) +
  theme_minimal(base_size = 13) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))
## Warning: Removed 811 rows containing non-finite outside the scale range
## (`stat_bin()`).

library(ggplot2)

ggplot(df, aes(x = Education, fill = Education)) +
  geom_bar(width = 0.7) +
  geom_text(stat = "count", aes(label = after_stat(count)), 
            vjust = -0.4, size = 4) +
  labs(
    title = "Phân bố trình độ học vấn (Education)",
    x = "Education",
    y = "Frequency",
    fill = "Education"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 30, hjust = 1),
    legend.position = "none"
  )

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# Tính trung vị theo Education
df_median <- df %>%
  group_by(Education) %>%
  summarise(Median_Income = median(HHIncomeMid, na.rm = TRUE))

# Vẽ biểu đồ
ggplot(df_median, aes(x = Education, y = Median_Income, fill = Education)) +
  geom_col(width = 0.7) +
  geom_text(aes(label = round(Median_Income, 0)), vjust = -0.4, size = 4) +
  labs(
    title = "Trung vị thu nhập hộ gia đình theo trình độ học vấn",
    x = "Education",
    y = "Median of HHIncomeMid",
    fill = "Education"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 30, hjust = 1),
    legend.position = "none"
  )

df_median_gender <- df %>%
  group_by(Gender) %>%
  summarise(Median_Income = median(HHIncomeMid, na.rm = TRUE))

ggplot(df_median_gender, aes(x = Gender, y = Median_Income, fill = Gender)) +
  geom_col(width = 0.6) +
  geom_text(aes(label = round(Median_Income, 0)), vjust = -0.4, size = 4.5) +
  labs(
    title = "Trung vị thu nhập hộ gia đình theo giới tính",
    x = "Gender",
    y = "Median of HHIncomeMid"
  ) +
  theme_minimal(base_size = 13) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        legend.position = "none")

library(ggplot2)
library(dplyr)

# Tính giá trị trung bình BMI theo Race1
df_bmi <- df %>%
  group_by(Race1) %>%
  summarise(Mean_BMI = mean(BMI, na.rm = TRUE))

# Vẽ biểu đồ
ggplot(df_bmi, aes(x = Race1, y = Mean_BMI, fill = Race1)) +
  geom_col(width = 0.7) +
  geom_text(aes(label = round(Mean_BMI, 1)), vjust = -0.4, size = 4) +
  labs(
    title = "Giá trị trung bình BMI theo chủng tộc (Race1)",
    x = "Race1",
    y = "Mean BMI",
    fill = "Race1"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 30, hjust = 1),
    legend.position = "none"
  )

library(ggplot2)

ggplot(df, aes(x = Race1, y = HHIncomeMid, fill = Race1)) +
  geom_boxplot(alpha = 0.8, outlier.shape = 21, outlier.size = 1.5) +
  labs(
    title = "Phân bố thu nhập hộ gia đình (HHIncomeMid) theo chủng tộc",
    x = "Race1",
    y = "HHIncomeMid",
    fill = "Race1"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 30, hjust = 1),
    legend.position = "none"
  )
## Warning: Removed 811 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

##8.3.6 Biểu đồ tương quan (scatterplot) giữa biến Age và BMI theo Race1, có đường mô tả mối liên quan giữa Age và BMI theo phương pháp loess (Locally Estimated Scatterplot Smoothing). Hãy tách thành biểu đồ riêng cho từng Race1.##

library(ggplot2)

ggplot(df, aes(x = Age, y = BMI)) +
  geom_point(alpha = 0.4, size = 1.2, color = "steelblue") +
  geom_smooth(method = "loess", se = TRUE, color = "red", linewidth = 1) +
  facet_wrap(~ Race1) +
  labs(
    title = "Mối liên quan giữa Age và BMI theo chủng tộc (Race1)",
    x = "Age (years)",
    y = "BMI",
    caption = "Đường đỏ: Loess smoothing"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    strip.text = element_text(face = "bold")
  )
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 366 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 366 rows containing missing values or values outside the scale range
## (`geom_point()`).

library(ggplot2)
library(dplyr)

# Lọc bỏ giá trị thiếu
df_clean <- df %>% 
  filter(!is.na(Age) & !is.na(BMI) & !is.na(Race1))

# Vẽ biểu đồ
ggplot(df_clean, aes(x = Age, y = BMI)) +
  geom_point(alpha = 0.4, size = 1.2, color = "steelblue") +
  geom_smooth(method = "loess", se = TRUE, color = "red", linewidth = 1) +
  facet_wrap(~ Race1) +
  labs(
    title = "Mối liên quan giữa Age và BMI theo chủng tộc (Race1)",
    x = "Age (years)",
    y = "BMI",
    caption = "Đường đỏ: Loess smoothing"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    strip.text = element_text(face = "bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

ggplot(df_clean, aes(x = Age, y = BMI, color = Race1)) +
  geom_point(alpha = 0.4, size = 1.2) +
  geom_smooth(method = "loess", se = FALSE, linewidth = 1.1) +
  labs(
    title = "Mối liên quan giữa Age và BMI theo chủng tộc",
    x = "Age (years)",
    y = "BMI",
    color = "Race1"
  ) +
  theme_minimal(base_size = 13) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))
## `geom_smooth()` using formula = 'y ~ x'