在 R 中使用 data.table 进行数据表连接
Scott Ritchie
Postdoctoral Researcher in Systems Genomics
当未使用正确列作为连接键时会怎样?
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)

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)

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

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

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

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

在连接前了解每列含义,可避免出错

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]


merge(purchases, web_visits, by = c("name", "date"))
merge(purchases, web_visits,
by.x = c("name", "date"),
by.y = c("person", "date")
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 进行数据表连接