r - How can I do a left join in data.table, Y[X], for two tables with different names, and keep the column names for X? -
when conducting left join using y[x] in data.table tables different names, retain column names table x, here denoted myx.
myx <- data.table(value = 1:10, key1 = letters[1:10], key2 = toupper(letters[1:10]) ) myy <- data.table(value2 = 101:120, diffkey1 = letters[1:20], diffkey2 = toupper(letters[1:20]) ) setkey(myx, 'key1', 'key2') setkey(myy, 'diffkey1', 'diffkey2') (myx <- myy[myx]) value2 diffkey1 diffkey2 value 1: 101 1 2: 102 b b 2 3: 103 c c 3 4: 104 d d 4 5: 105 e e 5 6: 106 f f 6 7: 107 g g 7 8: 108 h h 8 9: 109 9 10: 110 j j 10 # step avoid setnames(myx, old = c('diffkey1', 'diffkey2'), new = c('key1', 'key2'))
at end have reset names , avoid step.
would consider changing name of key @ beginning?
myx <- data.table(value = 1:10, key1 = letters[1:10], key2 = toupper(letters[1:10]) ) myy <- data.table(value2 = 101:120, key1 = letters[1:20], key2 = toupper(letters[1:20]) ) setkey(myx, 'key1', 'key2') setkey(myy, 'key1', 'key2') (myx <- myy[myx])
or can reverse everything
library(data.table) myx <- data.table(value = 1:10, diffkey1 = letters[1:10], diffkey2 = toupper(letters[1:10]) ) myy <- data.table(value2 = 101:120, key1 = letters[1:20], key2 = toupper(letters[1:20]) ) setkey(myx, 'diffkey1', 'diffkey2') setkey(myy, 'key1', 'key2') (myx <- myy[myx])
Comments
Post a Comment