Skip to content
Advertisement

Sort by custom function in R

In python, I can do something like

JavaScript

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

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

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