我有一个正负整数矩阵。我想把所有的东西加在一起 在特定列中具有相反符号的任何两行的可能组合(在下面的示例中为“a”列),使得此添加在该列中给出零。
合并的行行放在newmat
中,newmat[,"a"]
只有零。
问题在于,对于较大的矩阵(> 500行),我的解决方案变得非常慢。
##initialize matrix
nof.rows <- 100
mat <- cbind(matrix(ncol=40, nrow=nof.rows, sample(40*nof.rows)),
matrix(ncol=6, nrow=nof.rows, c(1,2,-1,3, -2, -3),
dimnames=list(seq_len(nof.rows),c("a", "b", "c", "d", "e", "f"))))
newmat <- matrix(ncol=ncol(mat), nrow=0)
##column which will contain nothing but zeroes
col <- "a"
for (i in seq_len(nrow(mat))){
curr.row <- mat[i,]
curr.col <- mat[,col]
opposite.sign.indices <- vector()
if(curr.row[col] > 0)
opposite.sign.indices <- which(curr.col<0)
else
opposite.sign.indices <- which(curr.col>0)
opposite.sign.indices <- setdiff(opposite.sign.indices, seq_len(i))
for (j in opposite.sign.indices){
opposite.sign.row <- mat[j,]
newrow <- (abs(opposite.sign.row[col]) * curr.row
+ (abs(curr.row[col])*opposite.sign.row))
newmat <- rbind(newmat, newrow)
}
}
newmat <- unique(newmat)
关于如何加快这一进程的任何想法?在此先感谢-H -
答案 0 :(得分:0)
这要快得多:
##initialize matrix
nof.rows <- 100
mat <- cbind(matrix(ncol=40, nrow=nof.rows, sample(40*nof.rows)),
matrix(ncol=6, nrow=nof.rows, c(1,2,-1,3, -2, -3),
dimnames=list(seq_len(nof.rows),c("a", "b", "c", "d", "e", "f"))))
col="a"
pos.row.idx <- which(mat[,col]>0)
neg.row.idx <- which(mat[,col]<0)
newmat <- unique(t(apply(expand.grid(pos.row.idx, neg.row.idx), 1, function(x){
abs(mat[x[2],col]) * mat[x[1],] + abs(mat[x[1],col]) * mat[x[2],]
})))