Search code examples
rshellmatrixrow

Replicate rows in Matrix


I have a matrix

A<- 
DOG.             4
CAT.             3
MOUSE.           6
PIG.             1
HORSE.           9

Names of animals are row names. Now I have the matrix :

B <- 
             A1.   A2.     A3.    A4.      A5.    A6.    
AGE.         16.   15.     4.      9.      11.    12pm

I would like to replicate the row age based on how many row names are in matrix A.

Example:

                  A1.   A2.     A3.    A4.      A5.    A6.    
DOG.             16.    15.      4.     9.      11.    12
CAT              16.    15.      4.     9.      11.    12
MOUSE            16.    15.      4.     9.      11.    12 
HORSE            16.    15.      4.     9.      11.    12
PIG              16.    15.      4.     9.      11.    12.

Suggestions?


Solution

  • Not sure what you are trying to do, but you can use replicate and assign the rownames after, i.e.

    m3 <- t(replicate(nrow(m1), m2[1,]))
    rownames(m3) <- rownames(m1)
    
    m3
    #      [,1] [,2] [,3] [,4] [,5] [,6]
    #DOG     16   15    4    9   11   12
    #CAT     16   15    4    9   11   12
    #MOUSE   16   15    4    9   11   12
    #PIG     16   15    4    9   11   12
    #HORSE   16   15    4    9   11   12
    

    WHERE

    dput(m1)
    structure(c("4", "3", "6", "1", "9"), .Dim = c(5L, 1L), .Dimnames = list(
        c("DOG", "CAT", "MOUSE", "PIG", "HORSE"), NULL))
    
    dput(m2)
    structure(c(16, 15, 4, 9, 11, 12), .Dim = c(1L, 6L), .Dimnames = list(
        "AGE", NULL))