检查table1中的id1是否等于table2中的id2,如果是,则将table1中的内容添加到id2的"order"中的table2(不改变顺序)

check if id1 in table1 equal to id2 in table2, if yes add content from table1 to table2 in the "order" of id2 (without changing order)

table1:

id1    fname      lname         by     bm   bd

 362   FRANK     MUELLER        1967    9   27
 55    MARTIN    SCHWARZ        1967    2   17
 116   HERBERT   ZIMMERMANN     1961    11  6
 326   HANS      SCHMITT        1945    8   14
 96    UWE         NA           2000    7   5

table2

id2

55
96
116
116
96

if table numeric id1 equal to numeric id2 in table2 添加列到 table2 匹配形式 table1 (fname, lname, by, bm, bd) 及其内容。 注意: 当添加到 table2 匹配来自 table1 的列时,应该按照 id2 的顺序(55,96,116,226,326,...)

当我这样做时,我使用了这个函数:merge(tabl2,table1,by="id2",sort=FALSE) 然后我得到了这个:

id2   fname      lname        by     bm   bd

55   MARTIN    SCHWARZ        1967    2   17
96   UWE         NA           2000    7   5
96   UWE         NA           2000    7   5
116  HERBERT   ZIMMERMANN     1961    11  6
116  HERBERT   ZIMMERMANN     1961    11  6
 .    .
 .    .

I got it with an order from a smaller number to the bigger number but what I want is to get the order as a column of id2 in table2 without changing the order of it.

您可以尝试(使用 base R):

df3 <- merge(df2, df1, by.x="id2", by.y="id1")

df3[match(df2$id2, df3$id2),]

这给了你

    id2   fname      lname   by bm bd
1    55  MARTIN    SCHWARZ 1967  2 17
2    96     UWE       <NA> 2000  7  5
4   116 HERBERT ZIMMERMANN 1961 11  6
4.1 116 HERBERT ZIMMERMANN 1961 11  6
2.1  96     UWE       <NA> 2000  7  5

使用dplyr

left_join(df2, df1, by=c("id2" = "id1"))

产量

# A tibble: 5 x 6
    id2 fname   lname         by    bm    bd
  <dbl> <chr>   <chr>      <dbl> <dbl> <dbl>
1    55 MARTIN  SCHWARZ     1967     2    17
2    96 UWE     NA          2000     7     5
3   116 HERBERT ZIMMERMANN  1961    11     6
4   116 HERBERT ZIMMERMANN  1961    11     6
5    96 UWE     NA          2000     7     5