matrix - how to merge matrices in R with different number of rows -


i merge several matrices using row names. these matrices not have same number of rows , columns. instance:

m1 <- matrix(c(1, 2, 3, 4, 5, 6), 3, 2) rownames(m1) <- c("a","b","c") m2 <- matrix(c(1, 2, 3, 5, 4, 5, 6, 2), 4, 2) rownames(m2) <- c("a", "b", "c", "d") m3 <- matrix(c(1, 2, 3, 4), 2,2) rownames(m3) <- c("d", "e")  mlist <- list(m1, m2, m3) 

for them get:

row.names    v1.x    v2.x    v1.y    v2.y   v1.z    v2.z             1       4       1       4      na      na         b     2       5       2       5      na      na         c     3       6       3       6      na      na         d    na      na       5       2       1       3         e    na      na      na      na       2       4 

i have tried use lapply function merge:

m <- lapply(mlist, merge, mlist, = "row.names", = true) 

however, did not work:

error in data.frame(c(1, 2, 3, 4, 5, 6), c(1, 2, 3, 5, 4, 5, 6, 2), c(1, :
arguments imply differing number of rows: 3, 4, 2

is there elegant way merge these matrices?

you trying apply reduction (?reduce) list of matrices, reduction merge. problem merge(m1, m2, = "row.names", = t) doesn't give new merged matrix row names, instead returns row names in first column. why need additional logic in reduction function.

reduce(function(a,b) {          res <- merge(a,b,by = "row.names", = t);           rn <- res[,1]; # row.names column of merge          res <- res[,-1]; # actual data          row.names(res) <- rn; # assign row.names          return(res) # return merged data proper row.names        },         mlist[-1], # reduce (left-to-right) applying function(a,b) repeatedly        init = mlist[[1]] # start first matrix ) 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -