R合并表,具有不同的列名并保留所有列

R merging tables, with different column names and retaining all columns

我有一项大工作要合并两个大 data.tables。这对我来说是新的,我需要向同事演示和解释。这就是偏执方法的原因,我想随机 select 一些结果行来向我们保证合并正在按照我们的想法进行!这是我的 MWE,谢谢。 J

library(data.table)
first <- data.table(index = c("a", "a", "b", "c", "c"),
                    type = 1:5,
                    value = 3:7)

second <- data.table(i2 = c("a", "a", "b", "c", "c"),
                    t2 = c(1:3, 7, 5), 
                    value = 5:9)

second[first , on=c(i2="index", t2="type"), nomatch=0L]

据我所知,这是正确的工作,并给出了这个结果


  i2 t2 value i.value
1:  a  1     5       3
2:  a  2     6       4
3:  b  3     7       5
4:  c  5     9       7

不过,如果可能的话,我希望保留两个表中的所有列,这样结果如下:

     i2     t2    index     type       value  i.value
1:  a        1      a         1          5       3
2:  a        2      a         2          6       4
3:  b        3      b         3          7       5
4:  c        5      c         5          9       7

是否可以保留所有列?

是的,这是可能的:

second[first, on=c(i2="index", t2="type"), nomatch=0L, .(i2, t2, index, type, value, i.value)]

   i2 t2 index type value i.value
1:  a  1     a    1     5       3
2:  a  2     a    2     6       4
3:  b  3     b    3     7       5
4:  c  5     c    5     9       7