0
votes

We have a matrix W and a list of 2500 matrices B, each matrice B (from 1 to 2500) has different column names (chr [1..80]).

  • W (nrow=100000, ncol=80)
  • each matrix B (nrow=1000, ncol=80)

For each element of this list, we have to create the same matrix W (that we already have) BUT with the corresponding B col names.

1
We can use Map, i.e. Map(function(x,y) {colnames(x) <- y; x}, replicate(length(lst), W, simplify=FALSE), lapply(B, colnames))akrun

1 Answers

0
votes

We can replicate the 'W' matrix to a list of 'W' matrices with length of the list equal to the length of list of 'B' matrices i.e. 'lst'. We extract the column names from each 'B' matrix in 'lst' using lapply. Then, pass these two as arguments to Map and assign the column names of the list of 'W' matrices with the corresponding list of column names.

res <-  Map(function(x,y) {
         colnames(x) <- y
         x}, replicate(length(lst), W, simplify=FALSE),
          lapply(B, colnames))

lapply(res, head, 2)
#[[1]]
#    A  B  C  D  E
#[1,] 1 21 41 61 81
#[2,] 2 22 42 62 82

#[[2]]
#    F  G  H  I  J
#[1,] 1 21 41 61 81
#[2,] 2 22 42 62 82

and the column names of 'B' matrices in 'lst' is

lapply(lst, colnames)
#[[1]]
#[1] "A" "B" "C" "D" "E"

#[[2]]
#[1] "F" "G" "H" "I" "J"

NOTE: Here I used a small dataset with 5 columns for 'B' and 'W' matrix and a list of length 2.

data

lst <- list(matrix(1:25, ncol=5, dimnames=list(NULL, 
   LETTERS[1:5])), matrix(26:50, ncol=5, 
      dimnames=list(NULL, LETTERS[6:10]))) 
W <- matrix(1:100, ncol=5)