sorting a complex vector by imaginary part in R

守給你的承諾、 提交于 2019-12-20 04:42:36

问题


roots <- polyroot(c(5, 4, 3, 2, 1))

I want to sort the roots by ascending order of the imaginary part. By default the sort function sorts it by the increasing order of the real part. I've read the document and I still do not know how to adjust the arguments or write the command. Can anybody help?


回答1:


Use Im function to extract the imaginary part and sort it.

roots <- polyroot(c(5, 4, 3, 2, 1))
#[1]  0.287815+1.416093i -1.287815+0.857897i -1.287815-0.857897i
#[4]  0.287815-1.416093i

roots[order(Im(roots))]
#[1]  0.287815-1.416093i -1.287815-0.857897i -1.287815+0.857897i
#[4]  0.287815+1.416093i



回答2:


This also works:

> roots<-polyroot(c(5,4,3,2,1))
> roots[sort(Im(roots),index.return=T)$ix]
[1]  0.287815-1.416093i -1.287815-0.857897i
[3] -1.287815+0.857897i  0.287815+1.416093i

Sort the complex numbers by their imaginary parts and return their indexes, then use the indexes to refer the corresponding complex value in the sorted order.



来源:https://stackoverflow.com/questions/52518107/sorting-a-complex-vector-by-imaginary-part-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!