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
source share