You can use the :=
operator along with the join simultaneously as follows:
First prepare data:
require(data.table) ## >= 1.9.0
setDT(x) ## converts DF to DT by reference
setDT(y)
setkey(x, key) ## set key column
setkey(y, key)
Now the one-liner:
x[y, c("a", "b") := list(i.a, i.b)]
:=
modifies by reference (in-place). The rows to modify are provided by the indices computed from the join in i
.
i.a
and i.b
are the column names data.table
internally generates for easy access to i
's columns when both x
and i
have identical column names, when performing a join of the form x[i]
.
HTH
PS: In your example y
's columns a and b are of type numeric and x
's are of type integer and therefore you'll get a warning when run on your data, that the types dint match and therefore a coercion had to take place.