[R] how to recode an ordered factor

William Dunlap wdunlap at tibco.com
Fri Dec 21 18:03:15 CET 2012


Will calling factor(var,levels=rev(levels(var))) work for you?

  > o <- factor(c("Good","Bad","Good","Neutral"), levels=c("Bad","Neutral","Good"), ordered=TRUE)
  > orev <- factor(o, levels=rev(levels(o)))
  > str(o)
   Ord.factor w/ 3 levels "Bad"<"Neutral"<..: 3 1 3 2
  > str(orev)
   Ord.factor w/ 3 levels "Good"<"Neutral"<..: 1 3 1 2
  > o
  [1] Good    Bad     Good    Neutral
  Levels: Bad < Neutral < Good
  > orev
  [1] Good    Bad     Good    Neutral
  Levels: Good < Neutral < Bad

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Francesco Sarracino
> Sent: Friday, December 21, 2012 8:44 AM
> To: r-help at r-project.org
> Subject: [R] how to recode an ordered factor
> 
> Dear R helpers,
> 
> I'm trying to recode an ordered factor to reverse its scale, but I can't
> figure out how to make it. I am using the Recode function provided by the
> Car package.
> 
> I've created an ordered variable:
> data$o.var1 <- ordered(data$var1, levels=c(1,2,3,4), labels =c("very
> satisfied", "fairly satisfied", "not very satisfied", "not at all
> satisfied"))
> 
> Now, I'd like to have a new variable ranging from 4 = Very satisfied to 1=
> not at all satisfied.
> 
> I've tried with the following:
> data$or.var1 <- Recode(data$o.var1, "1 = 4; 2 = 3; 3=2; 4=1")
> but it looks like the new variable loses the order:
> the output of table(data$or.var1) looks like:
> 
> fairly satisfied not at all satisfied not very satisfied very satisfied
> 
> I believe the new variable is ordered in alphabetical order, but when I
> tried to use the levels option I lost the initial information.
> Can you help figuring out what I am doing wrong?
> thanks in advance,
> f.
> 
> 
> 
> 
> 
> --
> Francesco Sarracino, Ph.D.
> https://sites.google.com/site/fsarracino/
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.




More information about the R-help mailing list