Home > Net >  Sort by custom function in R
Sort by custom function in R

Time:03-22

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)

CodePudding user response:

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)

CodePudding user response:

order takes the function of the sorting key lambda

a[order(a<0, abs(a))]

CodePudding user response:

How about using factor with levels?

a <-  c(1, 100, 5, -5, -7, 99, -100)
res <- factor(x = a, levels = unique(a[order(abs(a))]), ordered = TRUE)

Results

res
# [1] 1    100  5    -5   -7   99   -100
# Levels: 1 < 5 < -5 < -7 < 99 < 100 < -100

Desired sorting order

unique(a[order(abs(a))])
# [1]    1    5   -5   -7   99  100 -100
  • Related