dimScale, rowScale, and colScale implement D1 %*% x %*% D2, D %*% x, and x %*% D for diagonal matrices D1, D2, and D with diagonal entries d1, d2, and d, respectively. Unlike the explicit products, these functions preserve dimnames(x) and symmetry where appropriate.

dimScale(x, d1 = sqrt(1/diag(x, names = FALSE)), d2 = d1)
rowScale(x, d)
colScale(x, d)

Arguments

x

a matrix, possibly inheriting from virtual class Matrix.

d1,d2,d

numeric vectors giving factors by which to scale the rows or columns of x; they are recycled as necessary.

Details

dimScale(x) (with d1 and d2 unset) is only roughly equivalent to cov2cor(x). cov2cor sets the diagonal entries of the result to 1 (exactly); dimScale does not.

Value

The result of scaling x, currently always inheriting from virtual class dMatrix.

It inherits from triangularMatrix if and only if x does. In the special case of dimScale(x, d1, d2) with identical d1 and d2, it inherits from symmetricMatrix if and only if x does.

Author

Mikael Jagan

See also

Examples

n <- 6L
(x <- forceSymmetric(matrix(1, n, n)))
#> 6 x 6 Matrix of class "dsyMatrix"
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    1    1    1    1    1
#> [2,]    1    1    1    1    1    1
#> [3,]    1    1    1    1    1    1
#> [4,]    1    1    1    1    1    1
#> [5,]    1    1    1    1    1    1
#> [6,]    1    1    1    1    1    1
dimnames(x) <- rep.int(list(letters[seq_len(n)]), 2L)

d <- seq_len(n)
(D <- Diagonal(x = d))
#> 6 x 6 diagonal matrix of class "ddiMatrix"
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    .    .    .    .    .
#> [2,]    .    2    .    .    .    .
#> [3,]    .    .    3    .    .    .
#> [4,]    .    .    .    4    .    .
#> [5,]    .    .    .    .    5    .
#> [6,]    .    .    .    .    .    6

(scx <- dimScale(x, d)) # symmetry and 'dimnames' kept
#> 6 x 6 Matrix of class "dsyMatrix"
#>   a  b  c  d  e  f
#> a 1  2  3  4  5  6
#> b 2  4  6  8 10 12
#> c 3  6  9 12 15 18
#> d 4  8 12 16 20 24
#> e 5 10 15 20 25 30
#> f 6 12 18 24 30 36
(mmx <- D %*% x %*% D) # symmetry and 'dimnames' lost
#> 6 x 6 Matrix of class "dgeMatrix"
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    1    2    3    4    5    6
#> [2,]    2    4    6    8   10   12
#> [3,]    3    6    9   12   15   18
#> [4,]    4    8   12   16   20   24
#> [5,]    5   10   15   20   25   30
#> [6,]    6   12   18   24   30   36
stopifnot(identical(unname(as(scx, "generalMatrix")), mmx))

rowScale(x, d)
#> 6 x 6 Matrix of class "dgeMatrix"
#>   a b c d e f
#> a 1 1 1 1 1 1
#> b 2 2 2 2 2 2
#> c 3 3 3 3 3 3
#> d 4 4 4 4 4 4
#> e 5 5 5 5 5 5
#> f 6 6 6 6 6 6
colScale(x, d)
#> 6 x 6 Matrix of class "dgeMatrix"
#>   a b c d e f
#> a 1 2 3 4 5 6
#> b 1 2 3 4 5 6
#> c 1 2 3 4 5 6
#> d 1 2 3 4 5 6
#> e 1 2 3 4 5 6
#> f 1 2 3 4 5 6