一致性

R 中的数据清洗

Maggie Matsui

Content Developer @ DataCamp

一致性

  • 单位或格式不一致
    • 温度:°C°F
    • 重量:kgglb
    • 货币:USD $、GBP £、JPY ¥
    • 日期:DD-MM-YYYYMM-DD-YYYYYYYY-MM-DD
R 中的数据清洗

一致性问题从何而来?

左侧:三个数据库的箭头指向一张数据表,表示多数据源。右侧:一个带光标的自由文本框和一台带键盘的电脑,表示数据录入错误。

R 中的数据清洗

发现一致性问题

head(nyc_temps)
         date temp
1  2019-04-01  4.2
2  2019-04-02  7.5
3  2019-04-03 12.2
4  2019-04-04 11.1
5  2019-04-05 41.5
6  2019-04-06 11.9
R 中的数据清洗

发现一致性问题

library(ggplot2)
ggplot(nyc_temps, aes(x = date, y = temp)) +
  geom_point()

由代码生成的图。可见有三处温度显著高于其他点。

R 中的数据清洗

如何处理?

  • 没有唯一最优方案,取决于数据。
  • 先研究数据来源

由代码生成的图。可见有三处温度显著高于其他点。

  • 4 月 7、16、23 日的数据来自外部来源,温度以 °F 计量
R 中的数据清洗

单位换算

$$\text{C} = (\text{F} - 32) \times \frac{5}{9}$$

ifelse(condition, value_if_true, value_if_false)

nyc_temps %>%
  mutate(temp_c = ifelse(temp > 50, (temp - 32) * 5 / 9, temp))
         date temp   temp_c
1  2019-04-01  4.2  4.20000
...
7  2019-04-07 58.5 14.72222
...
R 中的数据清洗

单位换算

nyc_temps %>%
  mutate(temp_c = ifelse(temp > 50, (temp - 32) * 5 / 9, temp)) %>%
  ggplot(aes(x = date, y = temp_c)) +
    geom_point()

由代码生成的图,这次没有明显离群值,因为已完成转换。

R 中的数据清洗

日期统一化

nyc_temps
             date temp_c
1      2019-11-23   5.12
2        01/15/19  -0.67
3  April 24, 2019  17.46
4        08/30/19  26.46
5 October 3, 2019  14.63
6      2019-03-17   3.47

 

日期字符串 Date 格式
"2019-11-23" "%Y-%m-%d"
"01/15/19" "%m/%d/%y"
"April 24, 2019" "%B %d, %Y"

 

在 R 控制台中查看 ?strptime

R 中的数据清洗

解析多种格式

library(lubridate)
parse_date_time(nyc_temps$date,
                orders = c("%Y-%m-%d", "%m/%d/%y", "%B %d, %Y"))
"2019-11-23 UTC" "2019-01-15 UTC" "2019-04-24 UTC" "2019-08-30 UTC"
"2019-10-03 UTC" "2019-03-17 UTC"
parse_date_time("Monday, January 3",
                orders = c("%Y-%m-%d", "%m/%d/%y", "%B %d, %Y"))
NA
R 中的数据清洗

含糊的日期

02/04/2019 是 2 月还是 4 月?

  • 取决于你的数据!

 

可选做法:

  • 视为缺失值
  • 若来自多数据源,可按来源推断
  • 结合数据集中其他信息推断
R 中的数据清洗

Vamos praticar!

R 中的数据清洗

Preparing Video For Download...