什么是整洁数据?

使用 tidyr 重塑数据

Jeroen Boeye

Head of Machine Learning, Faktion

 

 

"幸福的家庭都相似,不幸的家庭各有各的不幸。"


列夫·托尔斯泰

 

"整洁的数据大同小异,混乱的数据各乱各的。"


Hadley Wickham

使用 tidyr 重塑数据

矩形数据

 

结构

  • 单元格

 

整洁示例

使用 tidyr 重塑数据

整洁数据:变量

 

结构

  • 列表示变量
  • 单元格

 

整洁示例:变量

使用 tidyr 重塑数据

整洁数据:观测

 

结构

  • 列表示变量
  • 行表示观测
  • 单元格

 

整洁示例:观测

使用 tidyr 重塑数据

整洁数据:值

 

结构

  • 列表示变量
  • 行表示观测
  • 单元格包含值

 

整洁示例:值

使用 tidyr 重塑数据

dplyr 回顾

character_df
# A tibble: 4 x 3
  name           homeworld species
  <chr>          <chr>     <chr>  
1 Luke Skywalker Tatooine  Human  
2 R2-D2          Naboo     Droid  
3 Darth Vader    Tatooine  Human  
4 Obi-Wan Kenobi Stewjon   Human
使用 tidyr 重塑数据

dplyr 回顾:select()

character_df %>% 
  select(name, homeworld)
# A tibble: 4 x 2
  name           homeworld
  <chr>          <chr>    
1 Luke Skywalker Tatooine 
2 R2-D2          Naboo    
3 Darth Vader    Tatooine 
4 Obi-Wan Kenobi Stewjon
使用 tidyr 重塑数据

dplyr 回顾:filter()

character_df %>% 
  filter(homeworld == "Tatooine")
# A tibble: 2 x 3
  name           homeworld species
  <chr>          <chr>     <chr>  
1 Luke Skywalker Tatooine  Human  
2 Darth Vader    Tatooine  Human
使用 tidyr 重塑数据

dplyr 回顾:mutate()

character_df %>% 
  mutate(is_human = species == "Human")
# A tibble: 4 x 4
  name           homeworld species is_human
  <chr>          <chr>     <chr>   <lgl>   
1 Luke Skywalker Tatooine  Human   TRUE    
2 R2-D2          Naboo     Droid   FALSE   
3 Darth Vader    Tatooine  Human   TRUE    
4 Obi-Wan Kenobi Stewjon   Human   TRUE
使用 tidyr 重塑数据

dplyr 回顾:group_by() 和 summarize()

character_df %>% 
  group_by(homeworld) %>% 
  summarize(n = n())
# A tibble: 3 x 2
  homeworld     n
  <chr>     <int>
1 Naboo         1
2 Stewjon       1
3 Tatooine      2
使用 tidyr 重塑数据

magrittr 标志

1 magrittr.tidyverse.org
使用 tidyr 重塑数据

 

dplyr 标志

 

tidyr 标志

1 www.tidyverse.org
使用 tidyr 重塑数据

单列包含多个变量

population_df
# A tibble: 4 x 2
  country                 population
  <chr>                        <dbl>
1 Brazil, South America        210. 
2 Nepal, Asia                   28.1
3 Senegal, Africa               15.8
4 Australia, Oceania            25.0
使用 tidyr 重塑数据

将变量拆分到两列

population_df %>% 
  separate(country, into = c("country", "continent"), sep = ", ")
# A tibble: 4 x 3
  country   continent      population
  <chr>     <chr>               <dbl>
1 Brazil    South America       210. 
2 Nepal     Asia                 28.1
3 Senegal   Africa               15.8
4 Australia Oceania              25.0
使用 tidyr 重塑数据

Passons à la pratique !

使用 tidyr 重塑数据

Preparing Video For Download...