提供欄位搬移輔助

使用 dplyr 進行程式設計

Dr. Chester Ismay

Educator, Data Scientist, and R/Python Consultant

world_bank_data 的欄名

names(world_bank_data)
 [1] "iso"                   "country"               "continent"            
 [4] "region"                "year"                  "infant_mortality_rate"
 [7] "fertility_rate"        "perc_electric_access"  "perc_college_complete"
[10] "perc_cvd_crd_70"       "unemployment_rate"     "perc_rural_pop"
使用 dplyr 進行程式設計

用 select() 移動欄位

reordered_wb <- world_bank_data %>% 
    select(iso:year,

matches("^perc"),
everything())
names(reordered_wb)
 [1] "iso"                   "country"               "continent"           
 [4] "region"                "year"                  "perc_electric_access" 
 [7] "perc_college_complete" "perc_cvd_crd_70"       "perc_rural_pop"       
[10] "infant_mortality_rate" "fertility_rate"        "unemployment_rate"
使用 dplyr 進行程式設計

改用 last_col()

world_bank_data %>% 
    select(iso:year, 
    matches("^perc"),

infant_mortality_rate:last_col()) %>%
names()
 [1] "iso"                   "country"               "continent"         
 [4] "region"                "year"                  "perc_electric_access" 
 [7] "perc_college_complete" "perc_cvd_crd_70"       "perc_rural_pop"       
[10] "infant_mortality_rate" "fertility_rate"        "unemployment_rate"
使用 dplyr 進行程式設計

用 relocate() 與 .after 更簡單

world_bank_data %>% 

relocate(matches("^perc"), .after = year) %>%
names()
 [1] "iso"                   "country"               "continent"           
 [4] "region"                "year"                  "perc_electric_access" 
 [7] "perc_college_complete" "perc_cvd_crd_70"       "perc_rural_pop"       
[10] "infant_mortality_rate" "fertility_rate"        "unemployment_rate"
使用 dplyr 進行程式設計

relocate() 搭配 .before

world_bank_data %>%
  relocate(matches("^perc"), 
           .before = infant_mortality_rate) %>%

names()
 [1] "iso"                   "country"               "continent"           
 [4] "region"                "year"                  "perc_electric_access" 
 [7] "perc_college_complete" "perc_cvd_crd_70"       "perc_rural_pop"       
[10] "infant_mortality_rate" "fertility_rate"        "unemployment_rate"
使用 dplyr 進行程式設計

一起來練習吧!

使用 dplyr 進行程式設計

Preparing Video For Download...