You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Changed behaviour in R 3.1.2 and data.table 1.9.4 when cross-joining two keyed data.tables #959
I use cross-joining a reasonable amount and wrote a function CJ.dt() #814 . Since the latest upgrades, this now NAs the values in the first table referenced. MRE below:
library(data.table)
a<- data.table(a=1:2, b=letters[1:2])
b<- data.table(c=3:4, d=letters[3:4])
CJ.dt<-function(X,Y) {
stopifnot(is.data.table(X),is.data.table(Y))
k<-NULL# Setting the variables to NULL first for CRAN check NOTE
setkey(X[,c(k=1,.SD)],k)[Y[,c(k=1,.SD)],allow.cartesian=TRUE][,k:=NULL]
}
#This works with unkeyed tablesab<-CJ.dt(a,b)
ab#This doesn't work with keyed tables
setkey(a,a)
setkey(b,c)
ab<-CJ.dt(a,b)
ab
It knows that there's no need to leave out the key here, as the data is still sorted by the key you set. So the join is happening against k of column a and c of b. You could just add setkey(Y, NULL) to your function to fix it:
library(data.table)
a<- data.table(a=1:2, b=letters[1:2])
b<- data.table(c=3:4, d=letters[3:4])
CJ.dt=function(X,Y) {
stopifnot(is.data.table(X),is.data.table(Y))
k=NULLX=X[, c(k=1, .SD)]
setkey(X, k)
Y=Y[, c(k=1, .SD)]
setkey(Y, NULL)
X[Y, allow.cartesian=TRUE][, k:=NULL][]
}
# worksab= CJ.dt(a,b)
ab# a b c d# 1: 1 a 3 c# 2: 2 b 3 c# 3: 1 a 4 d# 4: 2 b 4 d# and works as well
setkey(a,a)
setkey(b,c)
ab= CJ.dt(a,b)
# a b c d# 1: 1 a 3 c# 2: 2 b 3 c# 3: 1 a 4 d# 4: 2 b 4 d
Activity
arunsrinivasan commentedon Nov 17, 2014
When opening an issue, there should've been a link asking to go through the contribution guidelines, which also links to the new How to file a bug report page. Please read that.
The reason the results are different is because
data.table v1.9.4+is smarter (in retaining keys).It knows that there's no need to leave out the key here, as the data is still sorted by the key you set. So the join is happening against
kof columnaandcofb. You could just addsetkey(Y, NULL)to your function to fix it: