# facing problem in setting order of the levels in factor

2 messages
Open this post in threaded view
|

## facing problem in setting order of the levels in factor

 Hi all, I'm just a beginner in R. I have a pretty basic doubt. This is the actual quote I wrote > x<-factor(c("M","F","M","T","M","T")) > levels(x)=c("M","F","T") > x [1] F M F T F T Levels: M F T > table(x) x M F T 1 3 2 Expectation: I just wanted to change my baselevel from F to M. with the number of M and F remaining constant What exactly happened: The values of F and M also get exchanged along with the change of base level from F to M ​Best,​ -- *Anant Saini* ------------------------------ *Indian Institute of Technology Bombay* *Mob: +91 - 9967687330 * *LinkedIn* : *in.linkedin.com/in/anantsaini*         [[alternative HTML version deleted]] ______________________________________________ [hidden email] mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.
Open this post in threaded view
|

## Re: facing problem in setting order of the levels in factor

 Hi, I think you are looking for this: y <- factor(x, levels=c("M","F","T")) If you use the function levels(), you change the labels, but not the order, so that the first level (previously "F") will now be labeled "M", the second (previously "M") will now be labeled "F" ,and so on. This explains why in the table(x) at the end you get the same frequencies in the same order, but the frequencies are associated with different labels/levels. To change the order of the levels (but without changing the actual data), you need to change the level argument of the factor() function. I hope this makes it clear, although I can imagine that my explanation is not crystal clear... Ivan -- Ivan Calandra, PhD Scientific Mediator University of Reims Champagne-Ardenne GEGENAA - EA 3795 CREA - 2 esplanade Roland Garros 51100 Reims, France +33(0)3 26 77 36 89 [hidden email] -- https://www.researchgate.net/profile/Ivan_Calandrahttps://publons.com/author/705639/Le 19/08/2016 à 12:13, Anant Saini a écrit : > Hi all, > > I'm just a beginner in R. I have a pretty basic doubt. This is the actual > quote I wrote >> x<-factor(c("M","F","M","T","M","T")) >> levels(x)=c("M","F","T") >> x > [1] F M F T F T > Levels: M F T >> table(x) > x > M F T > 1 3 2 > > Expectation: I just wanted to change my baselevel from F to M. with the > number of M and F remaining constant > > What exactly happened: The values of F and M also get exchanged along with > the change of base level from F to M > > > ​Best,​ > ______________________________________________ [hidden email] mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.