In R, what is the easiest way to scale a vector to a unit vector?

In R, what is the easiest way to scale a vector to a unit vector?

For example, suppose that

>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 any built-in function in R?

+5
source share
2 answers

You can 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 
+7
source

The ppls package contains the normalize.vector function, which does exactly what you want. However, downloading a package doesn’t seem much easier than entering a function line directly ...

The fact that the ppls package implements the function probably means that to achieve this goal there is no standard function R. (Unless, of course, the author of ppls simply did not know about the standard function ...)

+2
source

Source: https://habr.com/ru/post/1208930/


All Articles