[R] Help: Sort components of a vector with indices tracked in R

0 views
Skip to first unread message

Chee Chen

unread,
Aug 23, 2011, 7:59:26 PM8/23/11
to R-ORG
Dear All,
I would like to know how to sort a vector of numeric values such that we know the original index of each ordered component. Say, we have
c <- c(1,4,3,2)
csort <- sort(c,descreasing=FALSE)
With a few components of c, we can manually find out:
csort[1] = 1 = c[1], ie, the original index of csort[1] is 1,
csort[2] =2 =c[4], ie, the original index of csort[2] is 4.

When length(c) is very large, manual checking is infeasible.
We can set up a for loop to compare and extract the index. However, is there an easier way to do this, so that the output is the sorted vector and their corresponding original indices.
Thanks
Chee
[[alternative HTML version deleted]]

______________________________________________
R-h...@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Justin Haynes

unread,
Aug 23, 2011, 8:16:10 PM8/23/11
to Chee Chen, R-ORG
If you make your vector a data.frame, you will have row numbers accompanying
your sorting

df<-data.frame(V1=c(1,4,3,2))
df$rows<-row.names(df)

df[order(df$V1),]

also, you shouldn't use c as a variable name since its an important R
function...

see your example :)

Justin

Reply all
Reply to author
Forward
0 new messages