Doc du lieu vao R

Đọc dữ liệu “obesity data” vào R và gọi đối tượng là “ob”

ob = read.csv ("~/Google Drive/NCKH/0 Nguyen Van Tuan/LOP NCKH 2020/TDTU Datasets for 2020 Workshop (1)/Obesity data.csv", header = TRUE)

Quan sat bo du lieu

Quan sát bộ dữ liệu 3 dong dau tien

##   id gender height weight  bmi age  bmc  bmd   fat  lean pcfat
## 1  1      F    150     49 21.8  53 1312 0.88 17802 28600  37.3
## 2  2      M    165     52 19.1  65 1309 0.84  8381 40229  16.8
## 3  3      F    157     57 23.1  64 1230 0.84 19221 36057  34.0

Tao ra bien moi OB dua vao BMI

Tạo ra biến mới gọi là “OB” dựa vào biến bmi: nếu bmi < 18.5 thì OB = “Underweight”; bmi từ 18.5 đến 24.9 thì OB=“Normal”; bmi từ 25.0 đến 29.9 thì OB=“Overweight”; bmi từ 30.0 trở lên, OB=“Obese”

ob$OB [ob$bmi < 18.5] = "Underweight"
ob$OB [ob$bmi >= 18.5 & ob$bmi < 24.9] = "Normal" 
ob$OB [ob$bmi >= 25.0 & ob$bmi < 29.9] = "Overweight" 
ob$OB [ob$bmi >= 30] = "Obese"
ob$OB = factor(ob$OB, levels=c("Underweight", "Normal", "Overweight", "Obese"))

Tìm hiểu phân bố của OB

library(ggplot2)
p = ggplot(data=ob, aes(OB, fill=OB)) + 
  geom_bar() 
p = p + 
  xlab("Obesity group") + 
  ylab("Frequency") 
p + theme(legend.position="none")

Vẽ biểu đồ tương quan giữa weight và pcfat dùng ggplot2

library(ggplot2)
library(ggthemes)
library(gridExtra)
p = ggplot(data=ob, aes(x=weight, y=pcfat))
p = p + geom_point() + geom_smooth()
p = p + xlab("Weight") + ylab("Percent body fat") + ggtitle("Weight and Percent Body Fat")
p = p + theme(plot.title=element_text(hjust=0.5)) 
p
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

Biểu đồ theo nhóm nam nữ

p = ggplot(data=ob, aes(x=weight, y=pcfat, fill=gender, col=gender))
p = p + geom_point() + geom_smooth()
p = p + xlab("Weight") + ylab("Percent body fat") + ggtitle("Weight and Percent Body Fat for men and women separately")
p = p + theme(plot.title=element_text(hjust=0.5))
p + theme_economist()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'