我有两个矩阵要加在一起,但它们有不同的尺寸。
我有一个更大的矩阵,包含所有可能的行和列:
> m1 <- cbind(a=c(x=1, y=2, z=3, w=4), b=c(5:8), c=c(9:6), d=c(5:2)) ; m1
a b c d
x 1 5 9 5
y 2 6 8 4
z 3 7 7 3
w 4 8 6 2
一个较小的矩阵,其中包含较大矩阵的行和列的子集:
> m2 <- cbind(b=c(y=5, z=7), c=c(2, 6)); m2
b c
y 5 2
z 7 6
是否有一种奇特的方法可以使m2
的尺寸达到&#34;符合&#34;到m1
的维度?
我想要的是以下内容:
> m3 <- cbind(a=c(x=NA, y=NA, z=NA, w=NA), b=c(NA, 5, 7, NA), c=c(NA, 2, 6, NA), d=c(rep(NA,4))) ; m3
a b c d
x NA NA NA NA
y NA 5 2 NA
z NA 7 6 NA
w NA NA NA NA
这样我就可以做到这样的事情:
> m1 + m3
a b c d
x NA NA NA NA
y NA 11 10 NA
z NA 14 13 NA
w NA NA NA NA
答案 0 :(得分:1)
调整理查德的回答:
mmconform <- function(smaller, larger) {
result <- unname(smaller)[match(rownames(larger), rownames(smaller)),
match(colnames(larger), colnames(smaller))]
dimnames(result) <- dimnames(larger)
result
}
很好地扩展了3d数组:
aaconform <- function(smaller, larger) {
result <- unname(smaller)[match(dimnames(larger)[[1]], dimnames(smaller)[[1]]),
match(dimnames(larger)[[2]], dimnames(smaller)[[2]]),
match(dimnames(larger)[[3]], dimnames(smaller)[[3]])]
dimnames(result) <- dimnames(larger)
result
}
答案 1 :(得分:1)
您还可以对属性使用match
。当找不到名称时,这将返回NA,从而插入所需的NA行和列。
> foo <- function(x, y) {
mat1 <- match(colnames(x), colnames(y))
mat2 <- match(rownames(x), rownames(y))
unname(y)[mat1, mat2]
}
> m1 + foo(m1, m2)
# a b c d
# x NA NA NA NA
# y NA 11 10 NA
# z NA 14 13 NA
# w NA NA NA NA
> m3 + foo(m3, m1)
# a b c d
# x NA NA NA NA
# y NA 11 10 NA
# z NA 14 13 NA
# w NA NA NA NA