Joining data tables

We can define one or more keys on data tables and use them for joins. Suppose a data table DT has a key defined. Then, if in DT[i, j, by], i is also a data table, R outer joins the two data tables on the key of DT. It joins the first key field of DT with the first column of i, the second key field of DT with the second column of i, and so on. If no keys are defined in DT, then R returns an error:

> emp <- read.csv("employees.csv", stringsAsFactors=FALSE) 
> dept <- read.csv("departments-1.csv", stringsAsFactors=FALSE) 
> empDT <- data.table(emp) 
> deptDT <- data.table(dept) 
> setkey(empDT,"DeptId") 

At this point, we have two data tables, empDT and deptDT, and a key field in empDT. The department ID in deptDT also happens ...

Get R Data Analysis Cookbook - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.