Scaling a matrix by row can be slightly slower due to a transposing step.
# S3 method for class 'matrix'
rowscale(x, center = TRUE, scale = TRUE)
A matrix with each row scaled.
mat <- matrix(rnorm(20), nrow=4)
rs.mat <- rowscale(mat)
print(mat)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.9112644 -1.525639735 -0.1926041 -1.0582966 1.3186982
#> [2,] -0.1679937 0.007670531 1.0293835 0.3827825 -0.5242241
#> [3,] 0.1264878 0.156114019 -0.2077972 -0.4486023 0.5624639
#> [4,] -0.3684058 -1.967901224 1.6174429 -0.2218656 -0.6634071
print(rs.mat)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.83369735 -1.1569752 -0.06803721 -0.77520921 1.1665242
#> [2,] -0.52930668 -0.2327354 1.49220681 0.40056027 -1.1307250
#> [3,] 0.23030980 0.3071870 -0.63712864 -1.26199532 1.3616271
#> [4,] -0.03704212 -1.2823267 1.50903718 0.07704649 -0.2667149
#> attr(,"scaled:center")
#> [1] -0.10931559 0.14552373 0.03773326 -0.32082737
#> attr(,"scaled:scale")
#> [1] 1.2241612 0.5923172 0.3853703 1.2844417
rowMeans(rs.mat)
#> [1] 0.000000e+00 4.440892e-17 -4.440892e-17 -9.992007e-17
apply(rs.mat, 1L, sd)
#> [1] 1 1 1 1
rowscale(mat, center=FALSE, scale=FALSE) ## equal to mat
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.9112644 -1.525639735 -0.1926041 -1.0582966 1.3186982
#> [2,] -0.1679937 0.007670531 1.0293835 0.3827825 -0.5242241
#> [3,] 0.1264878 0.156114019 -0.2077972 -0.4486023 0.5624639
#> [4,] -0.3684058 -1.967901224 1.6174429 -0.2218656 -0.6634071
rowscale(mat, center=TRUE, scale=FALSE)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1.02057997 -1.4163241 -0.08328852 -0.94898106 1.4280138
#> [2,] -0.31351745 -0.1378532 0.88385975 0.23725873 -0.6697478
#> [3,] 0.08875456 0.1183808 -0.24553046 -0.48633553 0.5247307
#> [4,] -0.04757844 -1.6470739 1.93827029 0.09896173 -0.3425797
#> attr(,"scaled:center")
#> [1] -0.10931559 0.14552373 0.03773326 -0.32082737
rowscale(mat, center=FALSE, scale=TRUE)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.7407165 -1.2401083 -0.1565572 -0.8602309 1.0718969
#> [2,] -0.2734911 0.0124875 1.6758201 0.6231638 -0.8534286
#> [3,] 0.3262749 0.4026955 -0.5360121 -1.1571679 1.4508737
#> [4,] -0.2762519 -1.4756456 1.2128518 -0.1663676 -0.4974608
#> attr(,"scaled:scale")
#> [1] 1.2302472 0.6142565 0.3876726 1.3335866