10

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?

smci
  • 32,567
  • 20
  • 113
  • 146
Tom
  • 3,168
  • 5
  • 27
  • 36

2 Answers2

12

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
  • 0.4082483 is not known and has to be calculated from vec. What I mean is that if there is a built-in function in R for this. For example, if there's some aaa by which aaa(vec, ...) = c(0.4082483, 0.0000000, 0.8164966, 0.4082483) – Tom Dec 13 '14 at 06:08
  • From my understanding there's no built in function to do `x / sqrt(sum(x^2))`, but you could make your own quick function. I edited the answer to reflect this. Does this help? –  Dec 13 '14 at 06:17
  • 1
    Thanks anyway. I also know this is a method and just wonder that there may be a built-in function in R for such a common calculation which I haven't found. – Tom Dec 13 '14 at 06:24
3

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.

Stibu
  • 15,166
  • 6
  • 57
  • 71
  • Unfortunately, `ppls` package is not available for R version 4.0.0. – Mehmet Yildirim May 29 '20 at 15:56
  • Yes, you are right. The package has been archived on 2020-05-14: https://cran.r-project.org/package=ppls – Stibu May 29 '20 at 15:59
  • How can anyone use it? Does it work with R's previous versions? – Mehmet Yildirim May 29 '20 at 16:36
  • The problem here is not that the package does not work with R 4.0.0, but that it has been archived on CRAN. You can not install it with `install.packages("ppls")` in any version of R. You can, however, still install the package with `install.packages("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, but that does not guarantee that all the functions will work correctly. – Stibu May 30 '20 at 08:15