简体   繁体   中英

merging matrix and vectors using R

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")))

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

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

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