一致性

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、4/16、4/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 的資料清理

一起來練習吧!

R 的資料清理

Preparing Video For Download...