In R, what's the simplest way to scale a vector to a unit vector?
You could make yourself a function:
scalar1 <- function(x) {x / sqrt(sum(x^2))}
Now just use:
> scalar1(vec)
[1] 0.4082483 0.0000000 0.8164966 0.4082483
The ppls
package contains the function normalize.vector
, which does exactly what you want. However, loading a package seems not much simpler than entering the one line definition of the function yourself...
Since 2020-05-04, ppls
has been retired on CRAN, such that it can no longer be installed with install.packages("ppls")
. It is still possible to install the latest version with
install.packages("https://cran.r-project.org/src/contrib/Archive/ppls/ppls_1.6-1.1.tar.gz", repos = NULL)
I have checked that installation works in R 4.0.0. Note, however, that this does not guarantee that all the functions will work correctly, and even less that they will do so with future versions of R.