I've got two matrix with same numbers of rows and columns, and I would like to merge them by their index in order to create a new matrix (I don't know nrow() nor ncol() in advance, nrow() comes from k kmeans clusters centroid and ncol() comes from k' knn values)
A <- matrix(sample(letters), ncol = 10, nrow = 3)
B <- matrix(sample(letters), ncol = 10, nrow = 3)
A
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "h" "p" "j" "w" "z" "e" "q" "o" "s" "y"
[2,] "y" "b" "k" "t" "a" "v" "f" "x" "c" "r"
[3,] "r" "i" "m" "g" "d" "n" "l" "u" "h" "p"
B
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "k" "q" "l" "n" "o" "r" "u" "b" "s" "y"
[2,] "y" "f" "v" "c" "t" "w" "h" "a" "d" "x"
[3,] "x" "e" "j" "g" "m" "i" "p" "z" "k" "q"
I find their index :
a <- which(A !=0, arr.ind = T)
b <- which(B !=0, arr.ind = T)
I would like a final matrix merging A and B by row and by column index, so that A[1,1] comes just before B[1,1]
A[1,1] B[1,1] A[1,2] B[1,2] A[1,3] B[1,3] A[1,4] B[1,4] ...
A[2,1] B[2,1] A[2,2]] B[2,2] A[2,3] B[2,3] A[2,4] B[2,4] ...
A[3,1] B[3,1] A[3,2] B[3,2] A[3,3] B[3,3] A[3,4] B[3,4] ...
So for instance first row would be :
h k p q j l w n z o
I found here that the lapply function does the job but it gives me a list :
t <- lapply(1:length(knn.mat),
function(i){cbind(A[i], B[i])})
I can't just unlist because I don't know in advance how many rows and columns my input matrix will have, and I would like a matrix or dataframe as an output, maybe something with a for loop that I could use with a function of the apply family ? (this one doesn't run well)
doMat <- function(x,y){
X <- matrix(0, nrow = nrow(x), ncol = ncol(x)*2)
for (i in 1:nrow(x))
{
X[i] <- cbind(x[i],y[i])
i = i+1
}
return(X)}