2

I'm using R and I have issues merging vectors in a matrix.

So, basicaly, here is what I have :

 A=
     ["A"] ["B"] ["C"] ["D"]
[1,]  0.2   0.1   0.2   0.8

B=
     ["A"] ["B"] ["E"] ["F"] ["G"]
[1,]  0.2   0.1   0.2    1    1.2

And I want my result to be :

C =
     ["A"] ["B"] ["E"] ["F"] ["G"] ["C"] ["D"]
[1,]  0.2   0.1   0.2    0     0    0.2   0.8
[2,]  0.2   0.1   0.2    1    1.2    0     0    

(the row order doesn't matter)


dput(a)
structure(c(0.2, 0.1, 0.2, 0.8), .Dim = c(1L, 4L), .Dimnames = list(NULL, c("A", "B", "C", "D")))

dput(b)
structure(c(0.2, 0.1, 0.2, 1, 1.2), .Dim = c(1L, 5L), .Dimnames = list(NULL, c("A", "B", "E", "F", "G")))
Andrie
  • 176,377
  • 47
  • 447
  • 496
Simon-Okp
  • 687
  • 7
  • 28
  • Please read http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and then provide us with some reproducible data. At the moment it's not clear what structure your data really is in, i.e. vectors or matrices. In short: paste the results of `dput(A)` and dput(`B`) into your question. – Andrie Mar 19 '12 at 14:35
  • Sorry about that, here are the dput() you asked for. dput(a) = structure(c(0.2, 0.1, 0.2, 0.8), .Dim = c(1L, 4L), .Dimnames = list(NULL, c("A", "B", "C", "D"))) dput(b) = structure(c(0.2, 0.1, 0.2, 1, 1.2), .Dim = c(1L, 5L), .Dimnames = list(NULL, c("A", "B", "E", "F", "G"))) – Simon-Okp Mar 19 '12 at 14:47

2 Answers2

2

You can create matrix C and then fill it with values from A and B:

C <- array(0, c(2,7), list(NULL, LETTERS[1:7]))
C[1, colnames(A)] <- A
C[2, colnames(B)] <- B
Ernest A
  • 7,526
  • 8
  • 34
  • 40
2

The plyr package has a rbind.fill for data.frames and rbind.fill.matrix for matrices:

library("plyr")
ab <- rbind.fill.matrix(a, b)
ab
#       A   B   C   D   E  F   G
# [1,] 0.2 0.1 0.2 0.8  NA NA  NA
# [2,] 0.2 0.1  NA  NA 0.2  1 1.2

As you can see, missing values are filled with NA but you can easily replace them with zeroes:

ab[is.na(ab)] <- 0
ab
#        A   B   C   D   E F   G
# [1,] 0.2 0.1 0.2 0.8 0.0 0 0.0
# [2,] 0.2 0.1 0.0 0.0 0.2 1 1.2
flodel
  • 87,577
  • 21
  • 185
  • 223