Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to join the two matrices by their column names and row names.

The elements in both matrices are numeric, and the merge value is to average the two matrices that have emerged together.

matrix1:

  A B C 

x 1 4 3

z 5 2 4

k 1 2 3

and matrix2:

  A B C D

x 6 4 1 2

y 2 3 1 3

z 1 4 1 4 

k 7 5 3 1

The output will be:

   A   B   C  D

x 3.5  4   2  2

y  2   3   1  3

z  3   3  2.5 4

k  4  3.5  3  1

My opinion is to use the for loop or apply function, but if the matrices are huge, then this program will run for a long time.

1 Answer

0 votes
by (107k points)

In R programming, you can use the rownames and colnames to subset matrix2 and update only part of it.

matrix2[rownames(matrix1), colnames(matrix1)] <- (matrix1 + matrix2[rownames(matrix1), colnames(matrix1)])/2

matrix2

#    A   B   C D

#x 3.5 4.0 2.0 2

#y 2.0 3.0 1.0 3

#z 3.0 3.0 2.5 4

#k 4.0 3.5 3.0 1

data

matrix1 <- structure(c(1L, 5L, 1L, 4L, 2L, 2L, 3L, 4L, 3L), .Dim = c(3L, 

           3L), .Dimnames = list(c("x", "z", "k"), c("A", "B", "C")))

matrix2 <- structure(c(6L, 2L, 1L, 7L, 4L, 3L, 4L, 5L, 1L, 1L, 1L, 3L, 2L, 

3L, 4L, 1L), .Dim = c(4L, 4L), .Dimnames = list(c("x", "y", "z", 

"k"), c("A", "B", "C", "D")))

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...