I have Ubuntu 16.04 and run R in terminal. I am working with big data tables, one has 75 millions rows and 11 columns (dt1) and another has 7 million rows and 7 columns (dt2). All values are numeric. Both tables have 'id' column'. I need to find all rows in the first one which have the same values for five columns as five columns in the second one, and change in the first data table 'id' value for these rows to the one in the second data table. In both data tables the compared columns have the same name, let us say that they are V1, V2, V3, V4 and V5. I've converted second data table to data frame format, so I can use its 'id' as index . I've tried it for 1000 first rows and it took 40 minutes.
for (i in 1:1000) {
dt1[(V1==dt2[i,V1] & V2==dt2[i,V2] &
V3==dt2[i,V3] & V4==dt2[i,V4] &
V5==dt2[i,V5]), id:=i]
}
I'm going to parallelize it, but due to memory constrictions I can use only 2 or 3 cores. Clearly it won't be sufficient. Are there quick and efficient ways to do it on my home comp? If to do it on AWS, what kind of tricks are useful there? In particular, how many cores may I use there simultaneously?
In R it is always preferable to avoid loops wherever possible, as they are usually much slower than alternative vectorized solutions.
This operation can be done with a data.table join. Basically, when you run
you are performing a right-join between the two data.tables. The preset key columns of
dt1
determine which columns to join on. Ifdt1
has no preset key, the operation fails. But you can specify theon
argument to manually select the key columns on-the-fly:(The alternative of course is to preset a key, using either
setkey()
orsetkeyv()
.)The above operation will actually just return a merged table containing data from both
dt1
anddt2
, which is not what you want. But we can make use of thej
argument of the data.table indexing function and the:=
in-place assignment syntax to assign theid
column ofdt2
to theid
column ofdt1
. Because we have a name conflict, we must usei.id
to reference theid
column ofdt2
, while the unmodified nameid
still refers to theid
column ofdt1
. This is simply the mechanism provided by data.table for disambiguating conflicting names. Hence, you're looking for:Here's an example that uses only two key columns and just a few rows of data (for simplicity). I also generated the keys to include some non-matching rows, just to demonstrate that the non-matching rows will have their ids left untouched by the operation.