Does anyone know how to sort a vector in R by absolute value, so (-2, 3, 1) -> (1, -2, 3)
etc?
If I were doing it in python I'd create a pair of every value and its sign, sort the list of pairs by the absolute value then reapply the sign, but I'm very new to R so have no idea how to do this.
Cheers
In Excel, there are two ways to sort numbers. In first, select the data and then click on the Sort option from the Data menu tab. Choose the column whose value we want to sort, then choose Sort on Value from the drop-down. Now we can Sort the number by Largest to Smallest and vice-versa.
To do this there is a function called ABS (absolute) which is very easy in that you just need to point at the cell i.e. =ABS(C2). The benefit of this is that you have a column to work with that can genuinely be matched by sorting, but you still have the original data.
In the Sort On list, choose Values, Cell Color, Font Color, or Cell Icon. In the Order list, choose the order that you want to apply to the sort operation—alphabetically or numerically, ascending or descending (that is, from A to Z (or Z to A) for text, or lower to higher, or higher to lower for numbers).
Go to Home → Conditional Formatting → Highlight Cell Rules → Less Than. Select the cells in which you want to highlight the negative numbers in red. In the Less Than dialog box, specify the value below which the formatting should be applied. ... Click OK.
@Arun's method is TRT:
v[order(abs(v))]
where v
is the vector to be sorted.
Notes:
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: v.sort(key=abs)
.N
times, not N*log(N)
times, which is especially important when the key is not cheap (unlike abs
or 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.See also:
sort
order
I found it useful to package this in a function so that I could pass a vector to it, and also so that there was the option of using other options in the order
function like decreasing
. It is essentially based on the existing answer.
sort_abs <- function(x, na.last = TRUE, decreasing = FALSE) {
x[order(abs(x), na.last = na.last, decreasing = decreasing)]
}
For example,
> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With