Anant Saini
2016-Aug-19 10:13 UTC
[R] 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* <http://in.linkedin.com/in/anantsaini> [[alternative HTML version deleted]]
Ivan Calandra
2016-Aug-19 13:10 UTC
[R] 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 ivan.calandra at univ-reims.fr -- https://www.researchgate.net/profile/Ivan_Calandra https://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,? >