資料型別限制

R 的資料清理

Maggie Matsui

Content Developer @ DataCamp

課程大綱

伺服器與放大鏡,標示「診斷髒資料」

R 的資料清理

課程大綱

伺服器與甲蟲,標示「髒資料的副作用」

R 的資料清理

課程大綱

圓形資料庫加掃把與亮光,代表乾淨資料

R 的資料清理

課程大綱

診斷髒資料、髒資料的副作用與清理髒資料

第 1 章-常見資料問題

R 的資料清理

為何需要乾淨資料?

 

資料科學流程:存取資料、探索與處理、擷取洞見、回報洞見

R 的資料清理

為何需要乾淨資料?

 

人為與技術錯誤

R 的資料清理

為何需要乾淨資料?

 

錯誤會在流程中擴散

R 的資料清理

資料型別限制

資料型別 範例
文字 名、姓、地址…
整數 訂閱數、售出產品數…
小數 溫度、匯率…
二元 是否已婚、新客戶、是/否…
類別 婚姻狀態、顏色…
日期 訂單日期、生日…
R 資料型別
character
integer
numeric
logical
factor
Date
R 的資料清理

快速瀏覽資料型別

sales <- read.csv("sales.csv")
head(sales)
  order_id revenue quantity
1     7432   5,454      494
2     7808   5,668      334
3     4893   4,062      259
4     6107   3,936       15
5     7661   1,067      307
6     5908   6,635      235
library(dplyr)
glimpse(sales)
Observations: 100
Variables: 3
$ order_id <dbl> 7432, 7808, ...
$ revenue  <chr> "$5454", "$5668", ...
$ quantity <dbl> 494, 334, ...
R 的資料清理

檢查資料型別

is.numeric(sales$revenue)
FALSE
library(assertive)
assert_is_numeric(sales$revenue)
Error: is_numeric : sales$revenue is not of class 'numeric'; it has class 'character'.
assert_is_numeric(sales$quantity)


R 的資料清理

檢查資料型別

邏輯檢查-回傳 TRUE/FALSE

  • is.character()
  • is.numeric()
  • is.logical()
  • is.factor()
  • is.Date()
  • ...

assertive 檢查-為 FALSE 時拋錯

  • assert_is_character()
  • assert_is_numeric()
  • assert_is_logical()
  • assert_is_factor()
  • assert_is_date()
  • ...
R 的資料清理

為何在意資料型別?

class(sales$revenue)
"character"
mean(sales$revenue)
NA
Warning message:
In mean.default(sales$revenue) :
  argument is not numeric or logical: returning NA
R 的資料清理

逗號造成的問題

sales$revenue
"5,454" "5,668" "4,062" "3,936" "1,067" ...

R 的資料清理

字元轉數值

library(stringr)
revenue_trimmed = str_remove(sales$revenue, ",")

revenue_trimmed
"5454" "5668" "4062" "3936" "1067" ...
as.numeric(revenue_trimmed)
5454 5668 4062 3936 1067 ...
R 的資料清理

整合應用

sales %>%
  mutate(revenue_usd = as.numeric(str_remove(revenue, ",")))
# A tibble: 100 x 4
   order_id revenue quantity revenue_usd
      <dbl> <chr>      <dbl>       <dbl>
 1     7432 5,454        494        5454
 2     7808 5,668        334        5668
 3     4893 4,062        259        4062
 4     6107 3,936         15        3936
 5     7661 1,067        307        1067
# ... with 95 more rows
R 的資料清理

同一函式,結果不同

mean(sales$revenue)
NA
Warning message:
In mean.default(sales$revenue) :
  argument is not numeric or logical: returning NA
mean(sales$revenue_usd)
5361.4
R 的資料清理

轉換資料型別

  • as.character()
  • as.numeric()
  • as.logical()
  • as.factor()
  • as.Date()
  • ...
R 的資料清理

注意:factor 轉 numeric

product_type
1000 1000 3000 2000 3000
Levels: 1000 2000 3000
class(product_type)
"factor"
as.numeric(product_type)
1 1 3 2 3
as.numeric(as.character(product_type))
1000 1000 3000 2000 3000
R 的資料清理

一起來練習吧!

R 的資料清理

Preparing Video For Download...