R – In R, what’s the simplest way to scale a vector to a unit vector

rscalingvector

In R, what's the simplest way to scale a vector to a unit vector?

For example, suppose

>vec
[1] 1 0 2 1

And

>vec / sqrt(sum(vec^2)) 
[1] 0.4082483 0.0000000 0.8164966 0.4082483

is its unit vector.

Is there some built-in function in R for this?

Best Answer

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