Reputation: 5
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]).
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.
Upvotes: 0
Views: 281
Reputation: 887851
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.
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)
Upvotes: 0