正と負の整数の行列があります。特定の列 (以下の例では列 "a") で反対の符号を持つ任意の 2 つの行のすべての可能な組み合わせを合計して、この列にゼロが追加されるようにします。
結合された行の行が挿入され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-