複雑なキー

R で学ぶ data.table によるデータ結合

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

誤指定の結合

結合キーに誤った列を使用するとどうなるか?

  • エラーが発生する
  • 不正な data.table が生成される
R で学ぶ data.table によるデータ結合

列の型の不一致

型が異なる結合キー列を使用するとエラーになります

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)

R で学ぶ data.table によるデータ結合

列の型の不一致

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)

R で学ぶ data.table によるデータ結合

不正な完全結合 - 共通キー値なし

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

R で学ぶ data.table によるデータ結合

不正な右・左結合 - 共通キー値なし

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

R で学ぶ data.table によるデータ結合

不正な内部結合 - 共通キー値なし

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

R で学ぶ data.table によるデータ結合

不正な結合 - 偶然一致したキー値

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

R で学ぶ data.table によるデータ結合

誤指定の結合を回避する

結合前に各列の意味を把握することで、エラーを防げます

R で学ぶ data.table によるデータ結合

異なる列名を持つキー

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]
R で学ぶ data.table によるデータ結合

複合キー

R で学ぶ data.table によるデータ結合

複合キー

R で学ぶ data.table によるデータ結合

merge() による複数キーの指定

merge(purchases, web_visits, by = c("name", "date"))
merge(purchases, web_visits, 
      by.x = c("name", "date"),  
      by.y = c("person", "date")
R で学ぶ data.table によるデータ結合

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")]
R で学ぶ data.table によるデータ結合

最終スライド

R で学ぶ data.table によるデータ結合

Preparing Video For Download...