I have a matrix with 10 columns named "PC1", "PC2" and so forth and another matrix containing certain columns names of the first matrix, which I'm supposed to extract.
First matrix containing my data:
set.seed(1234)
A <- matrix(rpois(50,9),nrow=5)
colnames(A) <- c("PC1","PC2","PC3","PC4","PC5","PC6","PC7","PC8","PC9","PC10")
A
PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 PC9 PC10
[1,] 14 13 10 6 13 8 8 9 4 6
[2,] 9 4 11 10 6 6 13 8 10 16
[3,] 12 8 13 12 9 10 17 15 10 8
[4,] 7 9 12 10 3 7 11 6 11 6
[5,] 7 8 5 7 8 7 17 5 6 9
Second matrix virtually telling me which columns to use from the first matrix:
B <- matrix(c("PC1","PC2","PC3","PC4","PC10"), nrow = 1, ncol = 5)
B
[,1] [,2] [,3] [,4] [,5]
[1,] "PC1" "PC2" "PC3" "PC4" "PC10"
What I'm aiming for is to get a third matrix containing the exact columns from matrix A, that are selected in matrix B. I've experimented with the match
function but since I'm new to R, I don't know if that's the correct strategy. My desired output would be something like this:
PC1 PC2 PC3 PC4 PC10
[1,] 14 13 10 6 6
[2,] 9 4 11 10 16
[3,] 12 8 13 12 8
[4,] 7 9 12 10 6
[5,] 7 8 5 7 9