[R] dividing a matrix by positive sum or negative sum depending on the sign

Hao Cen hcen at andrew.cmu.edu
Wed Nov 11 15:38:55 CET 2009


Hi,

I have a matrix with positive numbers, negative numbers, and NAs. An
example of the matrix is as follows

-1 -1 2 NA
3 3 -2 -1
1 1 NA -2

I need to compute a scaled version of this matrix. The scaling method is
dividing each positive numbers in each row by the sum of positive numbers
in that row and  dividing each negative numbers in each row by the sum of
absolute value of negative numbers in that row.

So the resulting matrix would be

-1/2 -1/2 2/2 NA
3/6 3/6 -2/3 -1/3
1/2 1/2 NA -2/2

Is there an efficient way to do that in R? One way I am using is

1. rowSums for positive numbers in the matrix
2. rowSums for negative numbers in the matrix
3. sweep(mat, 1, posSumVec, posDivFun)
4. sweep(mat, 1, negSumVec, negDivFun)

posDivFun = function(x,y) {
        xPosId = x>0 & !is.na(x)
        x[xPosId] = x[xPosId]/y[xPosId]
        return(x)
}

negDivFun = function(x,y) {
        xNegId = x<0 & !is.na(x)
        x[xNegId] = -x[xNegId]/y[xNegId]
        return(x)
}

It is not fast enough though. This scaling is to be applied to large data
sets repetitively. I would like to make it as fast as possible. Any
thoughts on improving it would be appreciated.

Thanks

Jeff




More information about the R-help mailing list