0

I have multiple (>2) matrices, each with col1 (positive double) and col2 (positive integer). They will always only have col1 and col2, but will have a variable number of rows each. I wish to merge them so shorter matrices are padded with -1 values. Example with 2 matrices:

matrix M1:

| col1_1 | col2_1 |
|--------|--------|
| 1      | 5      |
| 2      | 6      |
| 3      | 7      |
| 4      | 8      |

matrix M2:

| col1_2 | col2_2 |
|--------|--------|
| 9      | 12     |
| 10     | 13     |
| 11     | 14     |

becomes:

| col1_1 | col2_1 | col1_2 | col2_2 |
|--------|--------|--------|--------|
| 1      | 5      | 9      | 12     |
| 2      | 6      | 10     | 13     |
| 3      | 7      | 11     | 14     |
| 4      | 8      | -1     | -1     |

Note that I actually wish to merge >2 matrices.

When I try merge, with or without the parameter all=TRUE:

M1 <- matrix(1:8, nrow=4, ncol=2)
colnames(M1) <- c("col1_1", "col2_1")
M2 <- matrix(9:14, nrow=3)
colnames(M2) <- c("col1_2", "col2_2")

merge(M1, M2)
>
   c1_1 c2_1 c1_2 c2_2
1     1    5    9   12
2     2    6    9   12
3     3    7    9   12
4     4    8    9   12
5     1    5   10   13
6     2    6   10   13
7     3    7   10   13
8     4    8   10   13
9     1    5   11   14
10    2    6   11   14
11    3    7   11   14
12    4    8   11   14
AndreyIto
  • 954
  • 1
  • 14
  • 35
  • This doesn't look like a merge to me. It seems you simply want to column-bind two (multiple) `data.frame`s. Could you please clarify? A merge requires a (multiple) key(s) by which you consolidate values from two different datasets. If this is in fact a merge, what are the key(s) according to which you'd like to merge the two `data.frame`s? – Maurits Evers Oct 15 '19 at 23:03
  • You *can* use `merge` to merge on the row numbers (which corresponds to column-binding entries but accounting for different number of rows): `merge(M1, M2, by = 0, all = T)`. This seems to be a duplicate of the linked post above. If this is in fact a different issue, please leave a comment and flag for re-open. – Maurits Evers Oct 15 '19 at 23:10

0 Answers0