Jeffrey Cexun Cai
2010-Sep-25 21:51 UTC
[R] Question on levels function and extracting the associated level number
> > Dear Sir/Madam, > > I have a quick question, which I hope someone can help. > > I am using the levels function in R, which helps to summarize the number of > factors that I have in a vector in an ordered manner. > > Using an already existing example: > > > state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa", > "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas", > "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa", > "sa", "act", "nsw", "vic", "vic", "act") > > > statef <- factor(state) > > > levels(statef) > > [1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa" > > > I will now like to go through the entire vector "state", and generate the > corresponding level. Using the example, there are 8 levels, and so I will > like to generate the corresponding vector (6, 5, 4, 2, 2, 3, .......1) which > is the "level number" corresponding to the vector "state". > > Any guidance/assistance will be much appreciated. Thank you so much!! > > sincerely, > Jeff >[[alternative HTML version deleted]]
Jorge Ivan Velez
2010-Sep-25 22:16 UTC
[R] Question on levels function and extracting the associated level number
Jeffrey, You can try> as.numeric(state)[1] 6 5 4 2 2 3 8 8 4 7 2 7 4 4 5 6 5 3 8 7 4 2 2 8 5 1 2 7 7 1 HTH, Jorge On Sat, Sep 25, 2010 at 5:51 PM, Jeffrey Cexun Cai <> wrote:> > > > Dear Sir/Madam, > > > > I have a quick question, which I hope someone can help. > > > > I am using the levels function in R, which helps to summarize the number > of > > factors that I have in a vector in an ordered manner. > > > > Using an already existing example: > > > > > state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa", > > "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas", > > "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa", > > "sa", "act", "nsw", "vic", "vic", "act") > > > > > statef <- factor(state) > > > > > levels(statef) > > > > [1] "act" "nsw" "nt" "qld" "sa" "tas" "vic" "wa" > > > > > > I will now like to go through the entire vector "state", and generate the > > corresponding level. Using the example, there are 8 levels, and so I will > > like to generate the corresponding vector (6, 5, 4, 2, 2, 3, .......1) > which > > is the "level number" corresponding to the vector "state". > > > > Any guidance/assistance will be much appreciated. Thank you so much!! > > > > sincerely, > > Jeff > > > > [[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]]