คีย์ที่ซับซ้อน

การ Join ข้อมูลด้วย data.table ใน R

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

การ join ที่ระบุผิดพลาด

จะเกิดอะไรขึ้นถ้าระบุคอลัมน์สำหรับ join key ไม่ถูกต้อง?

  • เกิดข้อผิดพลาด
  • ได้ data.table ที่มีโครงสร้างผิดพลาด
การ Join ข้อมูลด้วย data.table ใน R

ชนิดข้อมูลของคอลัมน์ไม่ตรงกัน

การใช้คอลัมน์ join key ที่มีชนิดข้อมูลต่างกันจะทำให้เกิดข้อผิดพลาด

customers[web_visits, on = .(age = name)]
Error in bmerge(i, x, leftcols, rightcols, io, xo, roll, rollends, 
nomatch,  : 
  typeof x.age (double) != typeof i.name (character)

การ Join ข้อมูลด้วย data.table ใน R

ชนิดข้อมูลของคอลัมน์ไม่ตรงกัน

customers[web_visits, on = .(id)]
Error in bmerge(i, x, leftcols, rightcols, io, xo, roll, rollends, 
nomatch,  : 
  typeof x.id (integer) != typeof i.id(character)

การ Join ข้อมูลด้วย data.table ใน R

Full join ที่ผิดพลาด — ไม่มีค่า key ร่วมกัน

merge(customers, web_visits, by.x = "address", by.y = "name", all = TRUE)

การ Join ข้อมูลด้วย data.table ใน R

Right join และ Left join ที่ผิดพลาด — ไม่มีค่า key ร่วมกัน

customers[web_visits, on = .(address = name)]

การ Join ข้อมูลด้วย data.table ใน R

Inner join ที่ผิดพลาด — ไม่มีค่า key ร่วมกัน

customers[web_visits, on = .(address = name), nomatch = 0]

การ Join ข้อมูลด้วย data.table ใน R

การ join ที่ผิดพลาด — ค่า key ร่วมกันโดยบังเอิญ

customers[web_visits, on = .(age = duration), nomatch = O]

การ Join ข้อมูลด้วย data.table ใน R

การหลีกเลี่ยงการ join ที่ระบุผิดพลาด

ทำความเข้าใจความหมายของแต่ละคอลัมน์ก่อน join จะช่วยหลีกเลี่ยงข้อผิดพลาดได้

การ Join ข้อมูลด้วย data.table ใน R

Key ที่ใช้ชื่อคอลัมน์ต่างกัน

merge(customers, web_visits, by.x = "name", by.y = "person")

customers[web_visits, on = .(name = person)] customers[web_visits, on = c("name" = "person")] key <- c("name" = "person") customers[web_visits, on = key]
การ Join ข้อมูลด้วย data.table ใน R

Key หลายคอลัมน์

การ Join ข้อมูลด้วย data.table ใน R

Key หลายคอลัมน์

การ Join ข้อมูลด้วย data.table ใน R

การระบุ key หลายคอลัมน์ด้วย merge()

merge(purchases, web_visits, by = c("name", "date"))
merge(purchases, web_visits, 
      by.x = c("name", "date"),  
      by.y = c("person", "date")
การ Join ข้อมูลด้วย data.table ใน R

การระบุ key หลายคอลัมน์ด้วย syntax ของ data.table

purchases[web_visits, on = .(name, date)]
purchases[web_visits, on = c("name", "date")]
purchases[web_visits, on = .(name = person, date)]
purchases[web_visits, on = c("name" = "person", "date")]
การ Join ข้อมูลด้วย data.table ใน R

สไลด์สุดท้าย

การ Join ข้อมูลด้วย data.table ใน R

Preparing Video For Download...