檢查是否屬於某集合

R 的資料清理

Maggie Matsui

Content Developer @ DataCamp

類別資料

  • 類別變數有固定且已知的一組可能值
資料 範例值
婚姻狀態 unmarriedmarried
家庭收入區間 0-20K20-40K、...
T 恤尺寸 SMLXL
R 的資料清理

因子(factor)

  • factor 中,每個類別以數值儲存,並有對應的標籤
資料 標籤 數值表示
婚姻狀態 unmarriedmarried 12
家庭收入區間 0-20K20-40K、... 12、...
T 恤尺寸 SMLXL 1234
R 的資料清理

因子階層(levels)

tshirt_size
L  XL XL L  M  M  M  L  XL L  S  M  M  S  S  M  XL S  L  S ... 
Levels: S M L XL
levels(tshirt_size)
"S"  "M"  "L"  "XL"
R 的資料清理

不屬於集合的值

  • factor 不能包含預先定義集合以外的值
資料 階層 不允許
婚姻狀態 unmarriedmarried divorced
家庭收入區間 0-20K20-40K、... 10-30K
T 恤尺寸 SMLXL S/M
R 的資料清理

這些值怎麼來的?

 

左側:資料輸入錯誤,包含可自由輸入的文字框與下拉選單。右側:剖析錯誤,由資料庫圖示表示。

R 的資料清理

篩選式連接:快速複習

  • 保留或移除第一個資料表的觀測值,不新增欄

標題:Semi-join。副標:X 中有哪些觀測同時也在 Y?左:單欄資料表 X,值為 a、b、c。右:單欄資料表 Y,值為 a、c、d。兩表中的 a 與 c 以線相連。X 中 a 與 c 的儲存格被標示。

R 的資料清理

篩選式連接:快速複習

  • 保留或移除第一個資料表的觀測值,不新增欄

標題:Anti-join。副標:X 中有哪些觀測不在 Y?左:單欄資料表 X,值為 a、b、c。右:單欄資料表 Y,值為 a、c、d。兩表中的 a 與 c 以線相連。X 中 b 的儲存格被標示。

R 的資料清理

血型範例

study_data
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
5 Jennifer 2019-12-17         Z+
6  Kennedy 2020-04-27         A+
7    Keith 2019-04-19        AB+
blood_types
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
R 的資料清理

血型範例

study_data
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
5 Jennifer 2019-12-17         Z+  <--
6  Kennedy 2020-04-27         A+
7    Keith 2019-04-19        AB+
blood_types
  blood_type
1         O-
2         O+
3         A-
4         A+
5         B+
6         B-
7        AB+
8        AB-
R 的資料清理

找出不屬於者

文氏圖。左圈為 study_data,右圈為 blood types。左側為 Z+。中間為 A-、O-、AB+、A+、O+、B-。右側為 B+、AB-。左側的 Z+ 以紅色標示。

R 的資料清理

Anti-join

study_data %>%
  anti_join(blood_types, by = "blood_type")
      name   birthday blood_type
1 Jennifer 2019-12-17         Z+
R 的資料清理

移除不屬於者

文氏圖。左圈為 study_data,右圈為 blood types。左側為 Z+。中間為 A-、O-、AB+、A+、O+、B-。右側為 B+、AB-。中間的血型以藍色標示。

R 的資料清理

Semi-join

study_data %>%
  semi_join(blood_types, by = "blood_type")
      name   birthday blood_type
1     Beth 2019-10-20         B-
2 Ignatius 2020-07-08         A-
3     Paul 2019-08-12         O+
4    Helen 2019-03-17         O-
5  Kennedy 2020-04-27         A+
6    Keith 2019-04-19        AB+
R 的資料清理

一起來練習吧!

R 的資料清理

Preparing Video For Download...