Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - retrieve row numbers after sorting

Tags:

sorting

r

I was wondering how I could retrieve the row numbers after having sorted my data.

Let us imagine my vector is this one:

vec = c("GET FRESH", "EASTENDERS", "WORLD CUP", "SPORT", "DYNASTY" )

and then I sort

sort(vec)
[1] "DYNASTY"    "EASTENDERS" "GET FRESH"  "SPORT"      "WORLD CUP" 

How could I get the row numbers of each case?

     vec          rownumber
[1,] "DYNASTY"    "5"      
[2,] "EASTENDERS" "2"      
[3,] "GET FRESH"  "1"      
[4,] "SPORT"      "4"      
[5,] "WORLD CUP"  "3" 
like image 925
giac Avatar asked Dec 07 '25 02:12

giac


1 Answers

Try with index.return=TRUE. It returns a list of sorted values and the index, which can be converted to 'data.frame'

data.frame(sort(vec, index.return=TRUE))
#           x ix
#1    DYNASTY  5
#2 EASTENDERS  2
#3  GET FRESH  1
#4      SPORT  4
#5  WORLD CUP  3
like image 64
akrun Avatar answered Dec 08 '25 16:12

akrun



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!