Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort odd and even numbers of an array in a specific format

Tags:

r

I have a vector like this

seq_vector <- c(3,12,5,9,11,8,4,6,7,11,15,3,9,10,12,2)

I want to format them in descending order of odd numbers, followed by ascending order of even numbers. Output of above seq_vector will be

new_seq_vector <- c(15,11,11,9,9,7,5,3,3,2,4,6,8,10,12,12)

Can you please help me with the logic of the same?

like image 875
vinodetrx Avatar asked Jan 19 '26 18:01

vinodetrx


1 Answers

Try x[order(x*v)] where v is -1 for odd, +1 for even.

Thanks to @lmo for this:

x[order( x*(-1)^x )]
# [1] 15 11 11  9  9  7  5  3  3  2  4  6  8 10 12 12

So v = (-1)^x here.


Some other ways to build v: @d.b's (-1)^(x %% 2); and mine, 1-2*(x %% 2).

(Thanks @d.b) If x contains negative integers, an additional sorting vector is needed:

# new example
x = c(2, 5, -15, -10, 1, -3, 12)
x[order(v <- (-1)^x, x*v)]
# [1]   5   1  -3 -15 -10   2  12
like image 152
Frank Avatar answered Jan 22 '26 06:01

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!