Reputation: 2593
I have two big matrices A
and B
with different dimensions. I want to order the rows of matrix B
with respect to rows of the matrix A
. and add the rows with values 0
to matrix B
, if that row does not exist in B
but in A
Here is the reproduceable example and expected output:
A<-matrix(c(1:40), ncol=8)
rownames(A)<-c("B", "A", "C", "D", "E")
> A
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
B 1 6 11 16 21 26 31 36
A 2 7 12 17 22 27 32 37
C 3 8 13 18 23 28 33 38
D 4 9 14 19 24 29 34 39
E 5 10 15 20 25 30 35 40
> B<-matrix(c(100:108),ncol=3)
rownames(B)<-c("A", "E", "C")
> B
[,1] [,2] [,3]
A 100 103 106
E 101 104 107
C 102 105 108
Here is the Expected output :
>B
[,1] [,2] [,3]
B 0 0 0
A 100 103 106
C 102 105 108
D 0 0 0
E 101 104 107
>
Would someone help me to implement this in R ?
Upvotes: 2
Views: 87
Reputation: 61947
Coming from a sql background this is what first came into my head. The other answers are much better.
A1 = cbind(id = rownames(A),as.data.frame(A), stringsAsFactors = FALSE)
B1 = cbind(id = rownames(B),as.data.frame(B), stringsAsFactors = FALSE)
AB = merge(A1, B1, by = "id", all = T)
AB1 = as.matrix(AB[,(dim(A1)[2] + 1) : dim(AB)[2]])
dimnames(AB1) = NULL
AB1[is.na(AB1)] = 0
rownames(AB1) = AB[,1]
(B = AB1[match(AB[,1],A1[,1]),])
Upvotes: 2
Reputation: 61154
Another way to do it
> temp <- A[,seq(ncol(B))]*0
> temp[rownames(B), ] <- B
> (B <- temp)
# [,1] [,2] [,3]
#B 0 0 0
#A 100 103 106
#C 102 105 108
#D 0 0 0
#E 101 104 107
Upvotes: 3
Reputation: 13122
A way could be:
res = as.table(array(0, c(nrow(A), ncol(B)), list(rownames(A), NULL)))
B2 = as.data.frame(as.table(B))
res[as.matrix(B2[1:2])] = B2[[3]]
res ##which can be converted back to a `colnames`less matrix
# A B C
#B 0 0 0
#A 100 103 106
#C 102 105 108
#D 0 0 0
#E 101 104 107
Upvotes: 2