我有一个内核矩阵,如下所示:
kern <- matrix(c(1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,1), dimnames=list(c("r1", "r1", "r3"), c("c1a", "c1b", "c2a", "c2b", "c3a", "c3b")), ncol=6, nrow=3)
> kern
c1a c1b c2a c2b c3a c3b
r1 1 1 0 0 0 0
r2 0 0 1 1 0 0
r3 0 0 1 1 1 1
现在我想应用行操作,例如kern[,c("c1b", "c2b", "c3b")]
单位矩阵。我知道这很容易通过从第三行中减去第二行来完成:
kern[3,] = kern[3,] - kern[2,]
,
但是R中是否有一个函数可以为我做到这一点?在另一个线程中发布的缩减行梯形表格的功能不是我需要的。
编辑
我有一个笨拙的解决方案
sub <- kern[,c("c1b", "c2b", "c3b")]
for (i in which(colnames(kern) %in% colnames(sub))){
##identify which columns have more than one entry
nonzero.row.idx <- which(kern[,i] != 0)
while(length(nonzero.row.idx) > 1){
row.combinations <- combn(nonzero.row.idx, 2)
for (j in ncol(row.combinations)){
r1.idx <- row.combinations[1,j]
r2.idx <- row.combinations[2,j]
r1 <- kern[r1.idx,]
r2 <- kern[r2.idx,]
if (min(r1 - r2) >=0)
kern[r1.idx, ] <- r1-r2
else if (min(r2 - r1) >=0)
kern[r2.idx, ] <- r2-r1
else
stop("Producing negative entries in row")
nonzero.row.idx <- which(kern[,i] != 0)
}
}
}
kern[,c("c1b", "c2b", "c3b")]
另外我忘了提到我不希望任何条目kern
是负面的。此代码适用于我的几个示例,但是,它很容易对许多其他矩阵造成麻烦。