我有两个不同维度的大矩阵A
和B
。我想根据矩阵B
的行来排序矩阵A
的行。并将值0
的行添加到矩阵B
,如果该行在B
但A
以下是可重现的示例和预期输出:
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
这是预期的输出:
>B
[,1] [,2] [,3]
B 0 0 0
A 100 103 106
C 102 105 108
D 0 0 0
E 101 104 107
>
有人会帮我在R中实现这个吗?
答案 0 :(得分:3)
另一种方法
> 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
答案 1 :(得分:2)
一种方式可能是:
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
答案 2 :(得分:2)
来自sql背景,这是我首先想到的。其他答案要好得多。
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]),])