In python, I can do something like
JavaScript
x
3
1
a = [1,100,5,-5,-7,99,-100]
2
a.sort(key= lambda x: (x<0,abs(x)))
3
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:
JavaScript
1
4
1
a = c(1,100,5,-5,-7,99,-100)
2
a[order(a < 0, abs(a))]
3
#> [1] 1 5 99 100 -5 -7 -100
4
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
JavaScript
1
8
1
class(a) <- "classa"
2
xtfrm.classa <- function(x) {
3
(a < 0) + abs(a)/1000
4
}
5
6
sort(a)
7
#> [1] 1 5 99 100 -5 -7 -100
8
Created on 2022-03-22 by the reprex package (v2.0.1)