[R] Recoding Variables in R

John Fox jfox at mcmaster.ca
Thu Jan 28 17:54:02 CET 2010


Dear Abraham,

If I follow correctly what you want to do, the following should do it:

> f <- factor(c(1, 1, 5, 5, 8, 8, 9, 9, 0, 0))
> f
 [1] 1 1 5 5 8 8 9 9 0 0
Levels: 0 1 5 8 9
> recode(f, " '1'=3; '5'=1; '0'=2; else=NA ")
 [1] 3    3    1    1    <NA> <NA> <NA> <NA> 2    2   
Levels: 1 2 3

I think that your problem was that you didn't distinguish correctly between
factor levels and their numeric encoding; factor levels should be quoted in
recode().

I hope this helps,
 John

--------------------------------
John Fox
Senator William McMaster 
  Professor of Social Statistics
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
web: socserv.mcmaster.ca/jfox


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On
> Behalf Of Mathew, Abraham T
> Sent: January-28-10 10:15 AM
> To: r-help at r-project.org
> Subject: [R] Recoding Variables in R
> 
> 
> 
> VAR 980490
> 
> Some people have suggested placing new limits on foreign
> 
> imports in order to protect American jobs. Others say
> 
> that such limits would raise consumer prices and hurt
> 
> American exports.
> 
> Do you FAVOR or OPPOSE placing new limits on imports, or
> 
> haven't you thought much about this?
> 
> 1. Favor
> 
> 5. Oppose
> 
> 8. DK
> 
> 9. NA; RF
> 
> 0. Haven't thought much about this
> 
> 
> 
> 
> 
> I am trying to recode the data for the following public opinion question
from
> the ANES. I would like to throw out 8 and 9. Furthermore, I would like to
> reorder the responses so that:
> 
> 1. Oppose (originally 5)
> 
> 2. Haven't though much about this (originally 0)
> 
> 3. favor (originally 1)
> 
> 
> 
> I tried the following, which did not work:
> 
> library(car)
> data96$V961327 <- recode(data96$V961327, "c(1)=2; c(2)=3; c(3)=1")
> 
> 
> 
> 
> 
> I also tried the following, which also did not work:
> 
> new <- as.numeric(data96$V961327)
> new
> data96$V961327 <- recode(new, "c(5)=1; c(0)=2; c(1)=3")
> 
> 
> 
> 
> 
> 
> 
> Help,
> 
> Abraham M
> 
> 
> 
> ______________________________________________
> 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