Skip to content
Advertisement

Sort by custom function in R

In python, I can do something like

a = [1,100,5,-5,-7,99,-100]
a.sort(key= lambda x: (x<0,abs(x)))

It gives me [1, 5, 99, 100, -5, -7, -100]

It is sorted by positive/negative number and abs value.

How can I do the same thing in R? Without splitting into positive and negative numbers?

a = c(1,100,5,-5,-7,99,-100)

Advertisement

Answer

Use the order() function:

a = c(1,100,5,-5,-7,99,-100)
a[order(a < 0, abs(a))]
#> [1]    1    5   99  100   -5   -7 -100

Created on 2022-03-22 by the reprex package (v2.0.1)

Another possibility which is useful in some situations is to define an xtfrm method for a class. For example, if you know the values are all less than 1000, you could use

class(a) <- "classa"
xtfrm.classa <- function(x) {
    (a < 0) + abs(a)/1000
}

sort(a)
#> [1]    1    5   99  100   -5   -7 -100

Created on 2022-03-22 by the reprex package (v2.0.1)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement