Does anyone know how to sort a vector in R by absolute value, so
(-2, 3, 1) -> (1, -2, 3)
@Arun's method is TRT:
v is the vector to be sorted.
abs(v)of the same size as
v. This is not very memory-efficient, but I don't think this can be avoided in
R, like it is done in, e.g., Lisp:
(sort #'< v :key #'abs)or Python:
N*log(N)times, which is especially important when the key is not cheap (unlike
absor a structure field).
abs(v)is garbage collected very soon, but its allocation (and, especially, garbage collection) are expensive for large vectors and may be actually problematic if the memory is tight.