R: How to match/join 2 matrices of different dimensions (nrow/ncol)? -


i want match/join 2 matrices, small 1 values should match in bigger 1 rownames/colnames. find this answer. however, cannot match locations codeline frn <- as.matrix(bigmatrix[[1]]) not work in case. answers of inner, outer ... join here did not help, want match/join on lot of different columns (and not e.g. costumerid x , customerid y).

as matrices use 126x104 , 193x193 matrices. prepared example data: 1. bigger matrix smaller 1 should included (the letters in original data set country names):

a = c("a", "b", "c", "d", "e", "f") full_matrix = matrix(nrow = length(a), ncol=length(a)) dimnames(full_matrix) <- list(levels(as.factor(a)), levels(as.factor(a)))  full_matrix     b  c  d  e  f na na na na na na b na na na na na na c na na na na na na d na na na na na na e na na na na na na f na na na na na na 

and smaller matrix:

matrix = matrix(c(2, 4, 3, 1, 5, 7, 3, 1, 6), nrow=3, ncol=3) dimnames(matrix) <- list(c("b","c","e"), c("a","b","f"))  matrix   b f b 2 1 3 c 4 5 1 e 3 7 6 

the result should so:

    b  c  d  e  f na na na na na na b  2  1 na na na  3 c  4  5 na na na  1 d na na na na na na e  3  7 na na na  6 f na na na na na na 

see below using r's match function (i renamed small matrix):

a = c("a", "b", "c", "d", "e", "f") full_matrix = matrix(nrow = length(a), ncol=length(a)) dimnames(full_matrix) <- list(levels(as.factor(a)), levels(as.factor(a)))  small_matrix = matrix(c(2, 4, 3, 1, 5, 7, 3, 1, 6), nrow=3, ncol=3) dimnames(small_matrix) <- list(as.factor(c("b","c","e")), as.factor(c("a","b","f"))) 

you can use:

rowmatch <- match(rownames(small_matrix), rownames(full_matrix)) colmatch <- match(colnames(small_matrix), colnames(full_matrix)) full_matrix[rowmatch, colmatch] <- small_matrix 

which gives desired output:

    b  c  d  e  f na na na na na na b  2  1 na na na  3 c  4  5 na na na  1 d na na na na na na e  3  7 na na na  6 f na na na na na na 

or alternatively, can use %in% slighly different syntax:

full_matrix[rownames(full_matrix) %in% rownames(small_matrix),              colnames(full_matrix) %in% colnames(small_matrix)] <- small_matrix 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -