Skip to content

how to recode an ordered factor

3 messages · Francesco Sarracino, William Dunlap, arun

#
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
#
HI,

May be this helps:

?dat1<-data.frame(var1=factor(rep(1:4,times=3)))
dat1<-transform(dat1,o.var1=ordered(var1,levels=c(1,2,3,4),labels=c("very
 satisfied", "fairly satisfied","not very satisfied", "not at all 
satisfied")))
dat2<-transform(dat1,or.var1=factor(o.var1,levels=rev(levels(o.var1))))
str(dat2)
#'data.frame':??? 12 obs. of? 3 variables:
# $ var1?? : Factor w/ 4 levels "1","2","3","4": 1 2 3 4 1 2 3 4 1 2 ...
# $ o.var1 : Ord.factor w/ 4 levels "very satisfied"<..: 1 2 3 4 1 2 3 4 1 2 ...
# $ or.var1: Ord.factor w/ 4 levels "not at all satisfied"<..: 4 3 2 1 4 3 2 1 4 3 ...
?levels(dat2[,2])
#[1] "very satisfied"?????? "fairly satisfied"???? "not very satisfied"? 
#[4] "not at all satisfied"
?levels(dat2[,3])
#[1] "not at all satisfied" "not very satisfied"?? "fairly satisfied"??? 
#[4] "very satisfied"??? 


#or
dat3<-transform(dat1,or.var1=reorder(o.var1,
 new.order=c("not at all satisfied","not very satisfied","fairly 
satisfied","very satisfied")))
?identical(dat3,dat2)
#[1] TRUE
A.K.



----- Original Message -----
From: Francesco Sarracino <f.sarracino at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Friday, December 21, 2012 11:43 AM
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.