Tom
Tom

Reputation: 3336

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

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?

Upvotes: 11

Views: 33404

Answers (2)

Stibu
Stibu

Reputation: 15897

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.

Upvotes: 3

user4275591
user4275591

Reputation:

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

Upvotes: 12

Related Questions