用于match
将行名和列名转换为索引,删除不匹配,然后使用矩阵索引进行替换:
一些样本数据:
set.seed(123)
m1 <- matrix(runif(25), 5, 5)
rownames(m1) <- paste0("r", 1:5)
colnames(m1) <- paste0("c", 1:5)
m1
# c1 c2 c3 c4 c5
# r1 0.2875775 0.0455565 0.9568333 0.89982497 0.8895393
# r2 0.7883051 0.5281055 0.4533342 0.24608773 0.6928034
# r3 0.4089769 0.8924190 0.6775706 0.04205953 0.6405068
# r4 0.8830174 0.5514350 0.5726334 0.32792072 0.9942698
# r5 0.9404673 0.4566147 0.1029247 0.95450365 0.6557058
m2 <- data.frame(x1 = c("r1", "r3", "r100"),
x2 = c("c2", "c3", "c5"),
val = c(1, 2, 3))
m2
# x1 x2 val
# 1 r1 c2 1
# 2 r3 c3 2
# 3 r100 c5 3
i1 <- match(m2$x1, rownames(m1))
i2 <- match(m2$x2, colnames(m1))
k <- !(is.na(i1) | is.na(i2))
m1[cbind(i1[k], i2[k])] <- m2$val[k]
m1
# c1 c2 c3 c4 c5
# r1 0.2875775 *1.0000000* 0.9568333 0.89982497 0.8895393
# r2 0.7883051 0.5281055 0.4533342 0.24608773 0.6928034
# r3 0.4089769 0.8924190 *2.0000000* 0.04205953 0.6405068
# r4 0.8830174 0.5514350 0.5726334 0.32792072 0.9942698
# r5 0.9404673 0.4566147 0.1029247 0.95450365 0.6557058