Sort by absolute value

Does anyone know how to sort a vector in R by absolute value, so (-2, 3, 1) -> (1, -2, 3) , etc.

If I did this in python, I would create a pair of each value and its sign, sort the list of pairs by absolute value, and then reapply the sign, but I am very new to R, so I have no idea how to do this.

Greetings

+6
source share
2 answers

The @Arun method is TRT:

 v[order(abs(v))] 

where v is the vector to be sorted.

Notes:

  • This creates a new abs(v) vector of the same size as v . This is not very memory efficient, but I don’t think it can be avoided in R , for example, Lisp: (sort #'< v :key #'abs) or Python: v.sort(key=abs) .
  • This temporal distribution of vectors is not necessarily bad: you lose memory but gain time because the access key is only called N times, not N*log(N) times, which is especially important when the key is not cheap (unlike abs or structure fields).
  • To be more precise, the abs(v) vector collects garbage very soon, but its allocation (and, especially, garbage collection ) are expensive for large vectors and can actually be problematic if the memory is dense.

See also:

+8
source

It was convenient for me to pack this into a function so that I could pass a vector to it, and also to use other options in the order function, for example decreasing . It is based on an existing answer .

 sort_abs <- function(x, na.last = TRUE, decreasing = FALSE) { x[order(abs(x), na.last = na.last, decreasing = decreasing)] } 

For instance,

 > sort_abs(c(-1,NA,2,-2)) [1] -1 2 -2 NA > sort_abs(c(-1,NA,2,-2), decreasing = TRUE, na.last = FALSE) [1] NA 2 -2 -1 
+1
source

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


All Articles