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.7159223 -1.0974077 -0.6296734 0.06943551 0.6037091
#> [2,] 1.8451492 0.1219960 -1.1738495 -0.37075953 1.1457107
#> [3,] -1.1105637 1.2632146 -1.5343853 -1.87846108 0.6115717
#> [4,] -0.5937707 0.3696355 1.6108456 -0.98662348 -1.9960416
print(rs.mat)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.9991610 -1.3132200 -0.7167594 0.1747530 0.8560654
#> [2,] 1.2767357 -0.1597719 -1.2400542 -0.5705579 0.6936484
#> [3,] -0.4191027 1.2936902 -0.7249100 -0.9731768 0.8234992
#> [4,] -0.2000955 0.5019709 1.4064823 -0.4863805 -1.2219773
#> attr(,"scaled:center")
#> [1] -0.06760283 0.31364940 -0.52972476 -0.31919092
#> attr(,"scaled:scale")
#> [1] 0.784183 1.199543 1.385911 1.372244
rowMeans(rs.mat)
#> [1] 2.220446e-17 0.000000e+00 -4.440892e-17 -4.440892e-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.7159223 -1.0974077 -0.6296734 0.06943551 0.6037091
#> [2,] 1.8451492 0.1219960 -1.1738495 -0.37075953 1.1457107
#> [3,] -1.1105637 1.2632146 -1.5343853 -1.87846108 0.6115717
#> [4,] -0.5937707 0.3696355 1.6108456 -0.98662348 -1.9960416
rowscale(mat, center=TRUE, scale=FALSE)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.7835251 -1.0298048 -0.5620706 0.1370383 0.6713120
#> [2,] 1.5314998 -0.1916534 -1.4874989 -0.6844089 0.8320614
#> [3,] -0.5808389 1.7929393 -1.0046606 -1.3487363 1.1412965
#> [4,] -0.2745798 0.6888264 1.9300366 -0.6674326 -1.6768506
#> attr(,"scaled:center")
#> [1] -0.06760283 0.31364940 -0.52972476 -0.31919092
rowscale(mat, center=FALSE, scale=TRUE)
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0.9087418 -1.39297268 -0.7992635 0.08813659 0.7663062
#> [2,] 1.4764150 0.09761636 -0.9392677 -0.29666704 0.9167522
#> [3,] -0.7368621 0.83814638 -1.0180689 -1.24636414 0.4057795
#> [4,] -0.4187712 0.26069440 1.1360881 -0.69584021 -1.4077569
#> attr(,"scaled:scale")
#> [1] 0.7878171 1.2497497 1.5071527 1.4178880