简体   繁体   中英

Matching multiple IDs in R

I have the following data

id1 A   id2 B   id3 C   id4 D
1   12  1   10  2   13  1   12
4   11  3   9   4   14  4   13
3   13  4   4   1   15  3   8
7   13  2   11  3   16  2   14
2   14  6   12  7   16  6   11

I want to match ids for 4 groups ( AD) to get the following table

id1.1   A1  id2.2   B2  id3.3   C3  id4.4   D4
    1   12      1   10      1   15      1   12
    2   14      2   11      2   13      2   14
    3   13      3    9      3   16      3    8
    4   11      4    4      4   14      4   13
    7   13      NA  NA      7   16     NA   NA

Is there any solution?

I think this is what you're after:

DFList = split.default(DF, rep(1:4, each=2))
Reduce(function(x,y) merge(x, y, by = 1, all = TRUE), DFList)

  id  A  B  C  D
1  1 12 10 15 12
2  2 14 11 13 14
3  3 13  9 16  8
4  4 11  4 14 13
5  6 NA 12 NA 11
6  7 13 NA 16 NA

That is, split your table into its component parts and then merge them.


How it works: rep(1:4, each=2) evaluates to c(1,1,2,2,3,3,4,4) and serves as a grouping variable for the columns: the first pair of columns go together, then the next pair, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM