Chee Chen
2011-Aug-23 23:59 UTC
[R] Help: Sort components of a vector with indices tracked in R
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]]
Justin Haynes
2011-Aug-24 00:16 UTC
[R] Help: Sort components of a vector with indices tracked in R
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 On Tue, Aug 23, 2011 at 4:59 PM, Chee Chen <chee.chen@yahoo.com> wrote:> 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-help@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. >[[alternative HTML version deleted]]
Apparently Analagous Threads
- Extract indices after comparing two vectors
- Help: extrac the first entry for each component of a list
- core dump during make check when building 64-bit R on Solaris8/9
- Help: find the index of the minimum of entries
- Help: read a proportion of high through-put data