1. Chuẩn bị dữ liệu

Đọc file csv

library(readr)
mydata <- read.csv("salaries.csv")

Đọc file txt

mydata2 <- read.csv("salaries.txt")

Đọc file exel

library(readxl)
mydata3 <- read_excel("salaries.xlsx")

Đọc nhiều sheet trong 1 file exel

library(openxlsx)
wb_obj <- loadWorkbook("salaries_next.xlsx")
sheet_names <- sheets(wb_obj)
for (i in 1 : length(sheet_names)){
  assign(sheet_names[i], readWorkbook(wb_obj, sheet = i))
}

1.1. Star Would

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
data("starwars")
head(starwars)
## # A tibble: 6 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Luke Sky…    172    77 blond      fair       blue            19   male  mascu…
## 2 C-3PO        167    75 <NA>       gold       yellow         112   none  mascu…
## 3 R2-D2         96    32 <NA>       white, bl… red             33   none  mascu…
## 4 Darth Va…    202   136 none       white      yellow          41.9 male  mascu…
## 5 Leia Org…    150    49 brown      light      brown           19   fema… femin…
## 6 Owen Lars    178   120 brown, gr… light      blue            52   male  mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>

Lựa chọn biến số

Hàm select: Chọn các biến cần lấy thông tin

# Chỉ chọn ra các biến name, height, gender
newdata <- select(starwars, name, height, gender)
head(newdata)
## # A tibble: 6 × 3
##   name           height gender   
##   <chr>           <int> <chr>    
## 1 Luke Skywalker    172 masculine
## 2 C-3PO             167 masculine
## 3 R2-D2              96 masculine
## 4 Darth Vader       202 masculine
## 5 Leia Organa       150 feminine 
## 6 Owen Lars         178 masculine
# Loại bỏ các biến birth_year, gender
newdata <- select(starwars, -birth_year, -gender)
head(newdata)
## # A tibble: 6 × 12
##   name      height  mass hair_color skin_color eye_color sex   homeworld species
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>     <chr> <chr>     <chr>  
## 1 Luke Sky…    172    77 blond      fair       blue      male  Tatooine  Human  
## 2 C-3PO        167    75 <NA>       gold       yellow    none  Tatooine  Droid  
## 3 R2-D2         96    32 <NA>       white, bl… red       none  Naboo     Droid  
## 4 Darth Va…    202   136 none       white      yellow    male  Tatooine  Human  
## 5 Leia Org…    150    49 brown      light      brown     fema… Alderaan  Human  
## 6 Owen Lars    178   120 brown, gr… light      blue      male  Tatooine  Human  
## # ℹ 3 more variables: films <list>, vehicles <list>, starships <list>

Lựa chọn quan sát

Hàm filter: Chọn các quan sát thoả mãn điều kiện

# Lựa chọn các nhân vật có giới tính là female
newdata <- filter(starwars, sex == "female")
newdata
## # A tibble: 16 × 14
##    name     height  mass hair_color skin_color eye_color birth_year sex   gender
##    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
##  1 Leia Or…    150  49   brown      light      brown             19 fema… femin…
##  2 Beru Wh…    165  75   brown      light      blue              47 fema… femin…
##  3 Mon Mot…    150  NA   auburn     fair       blue              48 fema… femin…
##  4 Shmi Sk…    163  NA   black      fair       brown             72 fema… femin…
##  5 Ayla Se…    178  55   none       blue       hazel             48 fema… femin…
##  6 Adi Gal…    184  50   none       dark       blue              NA fema… femin…
##  7 Cordé       157  NA   brown      light      brown             NA fema… femin…
##  8 Luminar…    170  56.2 black      yellow     blue              58 fema… femin…
##  9 Barriss…    166  50   black      yellow     blue              40 fema… femin…
## 10 Dormé       165  NA   brown      light      brown             NA fema… femin…
## 11 Zam Wes…    168  55   blonde     fair, gre… yellow            NA fema… femin…
## 12 Taun We     213  NA   none       grey       black             NA fema… femin…
## 13 Jocasta…    167  NA   white      fair       blue              NA fema… femin…
## 14 Shaak Ti    178  57   none       red, blue… black             NA fema… femin…
## 15 Rey          NA  NA   brown      light      hazel             NA fema… femin…
## 16 Padmé A…    165  45   brown      light      brown             46 fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>
# Lựa chọn các nhân vật có giới tính là female và từ Alderaan
newdata <- filter(starwars, sex == "female" & homeworld == "Alderaan")
newdata
## # A tibble: 1 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Leia Org…    150    49 brown      light      brown             19 fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>
# Lựa chọn các nhân vật có giới tính là female và đến từ Alderaan, Coruscant, Endor
newdata <- filter(starwars, sex == "female", homeworld == "Alderaan" | homeworld == "Coruscant"| homeworld == "Endor")
newdata
## # A tibble: 3 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Leia Org…    150    49 brown      light      brown             19 fema… femin…
## 2 Adi Gall…    184    50 none       dark       blue              NA fema… femin…
## 3 Jocasta …    167    NA white      fair       blue              NA fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>
# Một cách khác ngắn gọn hơn sử dụng %in%
newdata <- filter(starwars, sex == "female", homeworld %in% c("Alderaan", "Coruscant", "Endor"))
newdata
## # A tibble: 3 × 14
##   name      height  mass hair_color skin_color eye_color birth_year sex   gender
##   <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
## 1 Leia Org…    150    49 brown      light      brown             19 fema… femin…
## 2 Adi Gall…    184    50 none       dark       blue              NA fema… femin…
## 3 Jocasta …    167    NA white      fair       blue              NA fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>

Tạo biến số mới

Hàm mutate: Tạo ra các biến số mới dựa trên các biến số có sẵn hoặc thay đổi các biến số đã có

Hàm ifelse: Điều kiện đi kèm với hàm mutate để thay đổi số liệu

# Chuyển biến số height từ cm sang đơn vị inch, biến số mass từ kilograms sang pounds
newdata <- mutate(starwars, height = height * 0.394, mass = mass * 2.205)
head(select(newdata, height, mass))
## # A tibble: 6 × 2
##   height  mass
##    <dbl> <dbl>
## 1   67.8 170. 
## 2   65.8 165. 
## 3   37.8  70.6
## 4   79.6 300. 
## 5   59.1 108. 
## 6   70.1 265.
# Nếu chiều cao trên 180 thì tall, dưới 180 thì shor
newdata <- mutate(starwars, heightcat = ifelse(height > 180, "tall", "short"))
head(select(newdata, height, heightcat))
## # A tibble: 6 × 2
##   height heightcat
##    <int> <chr>    
## 1    172 short    
## 2    167 short    
## 3     96 short    
## 4    202 tall     
## 5    150 short    
## 6    178 short
# Nếu chiều cao nhỏ hơn 75 hoặc lớn hơn 200 thì để trống, ngược lại giữ nguyên
newdata <- mutate(starwars,height = ifelse(height < 75 | height > 200, NA, height))
head(select(newdata, height))
## # A tibble: 6 × 1
##   height
##    <int>
## 1    172
## 2    167
## 3     96
## 4     NA
## 5    150
## 6    178

Thống kê dữ liệu

Hàm summarize: Tính toán giá trị trung bình các tham số thống kê với các biến số

Hàm group_by: Đi kèm với hàm summarize để tính toán thống kê theo nhóm

# Tính toán chiều cao trung bình và cân nặng trung bình
# Tham số na.rm = TRUE để loại bỏ các giá trị bị trống khi tính toán
newdata <- summarize(starwars, mean_ht = mean(height, na.rm = TRUE), mean_mass = mean(mass, na.rm = TRUE))
newdata
## # A tibble: 1 × 2
##   mean_ht mean_mass
##     <dbl>     <dbl>
## 1    174.      97.3
# Tính toán giá trị trung bình của height và mass theo gender
newdata <- group_by(starwars, gender)
newdata <- summarize(newdata, mean_ht = mean(height, na.rm = TRUE), mean_mass = mean(mass, na.rm = TRUE))
newdata
## # A tibble: 3 × 3
##   gender    mean_ht mean_mass
##   <chr>       <dbl>     <dbl>
## 1 feminine     165.      54.7
## 2 masculine    177.     106. 
## 3 <NA>         181.      48

Toán tử pipe

# Từ tập dữ liệu Starwars, giới tính là 'female', theo nhóm 'species', tính trung bình theo chiều cao 'height'
newdata <- starwars %>% 
  filter(sex == "female") %>% 
  group_by(species) %>% 
  summarize(mean_ht = mean(height, na.rm = TRUE))
newdata
## # A tibble: 7 × 2
##   species    mean_ht
##   <chr>        <dbl>
## 1 Clawdite      168 
## 2 Human         160.
## 3 Kaminoan      213 
## 4 Mirialan      168 
## 5 Tholothian    184 
## 6 Togruta       178 
## 7 Twi'lek       178

Định hình dữ liệu

library(tidyr)
# Tạo dữ liệu dạng wide format
id <- 1:3
name <- c("Bill", "Bob", "Marry")
sex <- c("Male", "Male", "Female")
age <- c(22,25,18)
income <- c(55000,75000,90000)
wide_data <- data.frame(id, name, sex, age, income)
wide_data
##   id  name    sex age income
## 1  1  Bill   Male  22  55000
## 2  2   Bob   Male  25  75000
## 3  3 Marry Female  18  90000
# Chuyển sang dữ liệu dạng long_format với hàm gather
long_data <- gather(wide_data, key = "variable", value = "value", sex : income)
long_data
##   id  name variable  value
## 1  1  Bill      sex   Male
## 2  2   Bob      sex   Male
## 3  3 Marry      sex Female
## 4  1  Bill      age     22
## 5  2   Bob      age     25
## 6  3 Marry      age     18
## 7  1  Bill   income  55000
## 8  2   Bob   income  75000
## 9  3 Marry   income  90000
# Chuyển từ dạng long_format sang wide_format với hàm spread
wide_data <- spread(long_data, variable, value)
wide_data
##   id  name age income    sex
## 1  1  Bill  22  55000   Male
## 2  2   Bob  25  75000   Male
## 3  3 Marry  18  90000 Female