Složené klíče

Joining Data with data.table in R

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

Chybně zadaná spojení

Co se stane, pokud použijete nesprávné sloupce jako klíče pro spojení?

  • Dojde k chybě
  • Výsledkem je chybně formátovaný data.table
Joining Data with data.table in R

Neshoda typů sloupců

Použití klíčových sloupců s různými typy způsobí chybu

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)

Joining Data with data.table in R

Neshoda typů sloupců

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)

Joining Data with data.table in R

Chybné úplné spojení – žádné společné hodnoty klíče

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

Joining Data with data.table in R

Chybná pravá a levá spojení – žádné společné hodnoty klíče

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

Joining Data with data.table in R

Chybné vnitřní spojení – žádné společné hodnoty klíče

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

Joining Data with data.table in R

Chybné spojení – náhodné shodné hodnoty klíče

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

Joining Data with data.table in R

Jak se vyhnout chybně zadaným spojením

Pochopení obsahu jednotlivých sloupců před spojením pomáhá předcházet chybám

Joining Data with data.table in R

Klíče s různými názvy sloupců

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]
Joining Data with data.table in R

Vícesloupcové klíče

Joining Data with data.table in R

Víceloupcové klíče

Joining Data with data.table in R

Zadání více klíčů pomocí merge()

merge(purchases, web_visits, by = c("name", "date"))
merge(purchases, web_visits, 
      by.x = c("name", "date"),  
      by.y = c("person", "date")
Joining Data with data.table in R

Zadání více klíčů se 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")]
Joining Data with data.table in R

Závěrečný snímek

Joining Data with data.table in R

Preparing Video For Download...