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
Post a Comment