Tobias Dekker
Tobias Dekker

Reputation: 1030

data.table inner join produces error when no match is found

I am trying to join two data.table using an inner join. It is possible that no matches could be found, then I want an empty data.table with the right col names.

dt1 <- data.table(A = c(1,2),  B = c(1,2))
dt2 <- data.table(A = c(3,4),  D = c(3,4))
setkey(dt1, A)
setkey(dt2, A)
dt1[dt2, nomatch = 0]
Error in xj[i] : invalid subscript type 'list'
merge(dt1, dt2, 
      all.x = F, 
      all.y = F)

Empty data.table (0 rows) of 3 cols: A,B,D

The second method gives me the desired answer. But I prefer the first syntax because it is faster. Does someone know how I could solve this error, without using a trycatch statement.

Upvotes: 0

Views: 105

Answers (2)

Wimpel
Wimpel

Reputation: 27732

I cannot reproduce your error from the first example.. I assume you mean

dt1[dt2, nomatch = 0]

?

I get:

Empty data.table (0 rows) of 3 cols: A,B,D

Using latest version of R and data.table

Upvotes: 1

clemens
clemens

Reputation: 6813

I think it is just a typo there:

library(data.table)
dt1 <- data.table(A = c(1,2),  B = c(1,2))
dt2 <- data.table(A = c(3,4),  D = c(3,4))

setkey(dt1, A)
setkey(dt2, A)
dt1[dt2, nomatch = 0] #instead of t1[t2, nomatch = 0]
Empty data.table (0 rows) of 3 cols: A,B,D

Upvotes: 0

Related Questions