-2

I want to sort a few complex numbers by ascending order of their imaginary parts. I've read the document but I still don't know how to do this in a single line command by using sort function. (I've tried r[order(Im(r))], which is the answer provided in a similar question, but I want to know how to do this by using sort. ) Can anyone help? Thanks.

Aria
  • 1
  • 2

1 Answers1

3

Different orderings of complex numbers are conceivable: e.g. according to their real part, imaginary part, magnitude or polar angle.

To sort according to their imaginary part, it's straightforward to define a custom function. Here is an example:

complex_sort  <- function(z) z[order(Im(z))]

z1 <- complex(real = 1, imaginary = 1)
z2 <- complex(real = 2, imaginary = 1)
z3 <- complex(real = 1, imaginary = 2)
complex_sort(c(z1, z2, z3))
#[1] 1+1i 2+1i 1+2i
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • @Ashley, you might also find it helpful to look at `help("complex")` which has a list of functions you can use to extract different parts of complex numbers in R – Scott Ritchie Oct 06 '18 at 14:13
  • Thanks for your answer. Actually I've tried this: `r<-polyroot(c(0,1,2,3,4,5)) r[order(Im(r))]` , but I wonder how to do the same thing by using `sort` in a single command? – Aria Oct 07 '18 at 06:13
  • @Aria You can't use `sort` as I explain in my post, hence my definition of function `complex_sort`. So to sort directly you can do `complex_sort(polyroot(c(0,1,2,3,4,5)))` – Maurits Evers Oct 07 '18 at 08:13
  • Hi! I figure out how to do this now: `roots<-polyroot(c(0,1,2,3,4,5)) roots[sort(Im(roots),index.return=T)$ix] [1] 0.1378323-0.6781544i -0.5378323-0.3582847i [3] 0.0000000+0.0000000i -0.5378323+0.3582847i [5] 0.1378323+0.6781544i` – Aria Oct 10 '18 at 11:33