user3525533
user3525533

Reputation: 435

how to change value of matrix with for loop using another matrix in r?

I have two matrix; m1 and m2

m1:
  a  b  c  d  e
x 0  0  0  0  0
y 0  0  0  0  0
x 0  0  0  0  0


m2:
  y
a 1.2
c 1.5
e 1.4

here is my code;

 for (i in 1:4){
   if colnames(m1[i]) in rownanmes(m2[i])
        m1["y", i] == m2[i]
 }

so far i got this matrix,

  a    b    c    d  e
x 0    0    0    0  0
y 1.2  1.5  1.4  NA NA
x 0    0    0    0  0

but I want to create matrix like this ;

  a    b  c    d  e
x 0    0  0    0  0
y 1.2  0  1.5  0  1.4
x 0    0  0    0  0

Any suggestion? thanks

Upvotes: 0

Views: 451

Answers (1)

akrun
akrun

Reputation: 887038

Another option is to do:

indx <- Map(intersect, dimnames(t(m2)), dimnames(m1))
m1[indx[[1]], indx[[2]]] <- m2[indx[[2]], indx[[1]]]
m1
#    a b   c d   e
#x 0.0 0 0.0 0 0.0
#y 1.2 0 1.5 0 1.4
#x 0.0 0 0.0 0 0.0

Update

Based on the dput output of m2 (in the comments), the colname of m2 is m2 and because there are no intersects between the rownames of m1 and colname of m2, when you use the code, it will not replace anything.

 m1[indx[[1]], indx[[2]]] <- m2[indx[[2]], indx[[1]]]
 m1
 #  a b c d e
 #x 0 0 0 0 0
 #y 0 0 0 0 0
 #x 0 0 0 0 0

data

m1 <-  structure(c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
  0L, 0L), .Dim = c(3L, 5L), .Dimnames = list(c("x", "y", "x"), 
   c("a", "b", "c", "d", "e")))

m2 <-  structure(c(1.2, 1.5, 1.4), .Dim = c(3L, 1L), .Dimnames = list(
        c("a", "c", "e"), "y"))

Upvotes: 1

Related Questions