Dear All: I'd like to know how to sort and then index a vector of floats by several levels in R. For example>x<-rnorm(100) > MyLevels<-quantile(x,probs=c(0,.5,1)) > MyLevels0% 50% 100% -2.11978442 -0.03770613 2.00186397 next i want to replace each x[i] in x by 1,2,3 or 4 depending on which quantile that x[i] falls. How do I do that in a "vector" fashion? I tried something like>factor(x,levels=as.numeric(MyLevels))but that doesnt work. Thank you very much, Vlad
morozov wrote:> Dear All: > I'd like to know how to sort and then index a vector of floats by several > levels in R. > For example > > > >>x<-rnorm(100) >>MyLevels<-quantile(x,probs=c(0,.5,1)) >>MyLevels > > 0% 50% 100% > -2.11978442 -0.03770613 2.00186397 > > next i want to replace each x[i] in x by 1,2,3 or 4 depending on which > quantile that x[i] falls. How do I do that in a "vector" fashion?I think rank() is the function you're looking for. Cheers Jason -- Indigo Industrial Controls Ltd. http://www.indigoindustrial.co.nz 64-21-343-545 jasont at indigoindustrial.co.nz
On Thu, 2003-10-02 at 12:40, morozov wrote:> Dear All: > I'd like to know how to sort and then index a vector of floats by several > levels in R. > For example > > > >x<-rnorm(100) > > MyLevels<-quantile(x,probs=c(0,.5,1)) > > MyLevels > 0% 50% 100% > -2.11978442 -0.03770613 2.00186397 > > next i want to replace each x[i] in x by 1,2,3 or 4 depending on which > quantile that x[i] falls. How do I do that in a "vector" fashion? > > I tried something like > > >factor(x,levels=as.numeric(MyLevels)) > > but that doesnt work. > > > Thank you very much, > VladYou might want to look at ?cut, which returns a factor based upon defining breakpoints in a continuous vector. You can break the vector 'x' and relabel the levels to give you what you need. For example: x <- rnorm(100) MyLevels <- factor(cut(x, quantile(x), include.lowest = TRUE), labels = 1:4) table(MyLevels) MyLevels 1 2 3 4 25 25 25 25 HTH, Marc Schwartz
morozov wrote:>>x<-rnorm(100) >>MyLevels<-quantile(x,probs=c(0,.5,1)) >>MyLevels > > 0% 50% 100% > -2.11978442 -0.03770613 2.00186397 > > next i want to replace each x[i] in x by 1,2,3 or 4 depending on which > quantile that x[i] falls. How do I do that in a "vector" fashion?Take a look at the "cut" function. -- Ross Ihaka Email: ihaka at stat.auckland.ac.nz Department of Statistics Phone: (64-9) 373-7599 x 85054 University of Auckland Fax: (64-9) 373-7018 Private Bag 92019, Auckland New Zealand