r - How to update a value of matrix by another matrix? -


i have 2 matrices: m1 , m2.

m1:

    1   2   3   4   5 1  v11 v12 v13 v14 v15 2  v21 v22 v23 v24 v25 3  v31 v32 v33 v34 v35  4  v41 v42 v43 v44 v45 5  v51 v52 v53 v54 v55 

m2:

 x1, x2, val  1   2    v1  2   3    v2  2   5    v3 

i update m1 if rowname , colname found in m2.

e.g. new value v12<-v12-v1 , new value v23<-v23-v2

so far try use:

m1[rownames(m1) %in% m2$x1 & colnames(m1) %in% m2$x2] 

or apply(m1, c(1,2), function(x)

i not right.

use match translate row , column names indices, remove mismatches, use matrix indexing replacements:

some sample data:

set.seed(123) m1 <- matrix(runif(25), 5, 5) rownames(m1) <- paste0("r", 1:5) colnames(m1) <- paste0("c", 1:5) m1 #           c1        c2        c3         c4        c5 # r1 0.2875775 0.0455565 0.9568333 0.89982497 0.8895393 # r2 0.7883051 0.5281055 0.4533342 0.24608773 0.6928034 # r3 0.4089769 0.8924190 0.6775706 0.04205953 0.6405068 # r4 0.8830174 0.5514350 0.5726334 0.32792072 0.9942698 # r5 0.9404673 0.4566147 0.1029247 0.95450365 0.6557058  m2 <- data.frame(x1  = c("r1", "r3", "r100"),                  x2  = c("c2", "c3", "c5"),                  val = c(1, 2, 3)) m2 #     x1 x2 val # 1   r1 c2   1 # 2   r3 c3   2 # 3 r100 c5   3 

i1 <- match(m2$x1, rownames(m1)) i2 <- match(m2$x2, colnames(m1)) k  <- !(is.na(i1) | is.na(i2))  m1[cbind(i1[k], i2[k])] <- m2$val[k] m1 #           c1        c2        c3         c4        c5 # r1 0.2875775 *1.0000000* 0.9568333  0.89982497 0.8895393 # r2 0.7883051  0.5281055  0.4533342  0.24608773 0.6928034 # r3 0.4089769  0.8924190 *2.0000000* 0.04205953 0.6405068 # r4 0.8830174  0.5514350  0.5726334  0.32792072 0.9942698 # r5 0.9404673  0.4566147  0.1029247  0.95450365 0.6557058 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -