[R] recode according to old levels

Peter Ehlers ehlers at ucalgary.ca
Wed Nov 18 11:55:53 CET 2009


Andreas Wittmann wrote:
> Dear R-users,
> 
> i try to recode a factor according to old levels
> 
> F <- factor(sample(c(rep("A", 4), rep("B",2), rep("C",5))))
> 
> recode(F, "levels(F)[c(1,3)]='X'; else='Y'")
> 
> i tried to work with eval or expression around levels(F)[c(1,3)], but 
> nothing seems to work.
> 
I assume that you mean the recode() function in pkg:car?
(You really should say so.)

Here are a couple of ways to recode the factor:

set.seed(6931)
F <- factor(sample(rep(c("A","B","C"), c(4,2,5))))
lev <- levels(F)

# 1: using car:::recode
F <- recode(F, "lev[c(1,3)] = 'X'; else = 'Y'")

# 2: using base:::levels
levels(F) <- list(X = lev[c(1,3)], Y = lev[-c(1,3)])

  -Peter Ehlers

> 
> Many thanks if anyone could tell me what i've missed and what's the 
> problem here.
> 
> best regards
> 
> Andreas
> 
> ______________________________________________
> 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