[R] Recoding categorical variables

John Fox jfox at mcmaster.ca
Thu Oct 26 02:50:27 CEST 2006


Dear Murray,

How about as.numeric(factor(y)) ?

I hope this helps,
 John

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox 
-------------------------------- 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Murray 
> Jorgensen
> Sent: Wednesday, October 25, 2006 7:13 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Recoding categorical variables
> 
> I want to recode an integer-valued variable y so that its 
> values become 1:length(y). I can do this using a loop but 
> maybe someone can suggest code without a loop. My code is this:
> 
> y <- round(20*runif(25))
> table(y)
> suy <- sort(unique(y))
> m <- length(suy)
> z <- y + max(suy)
> for(i in 1:m) z[y==suy[i]] <- i
> rbind(y,z)
> 
> (the recoded y is stored in z)
> 
> Murray Jorgensen
> -- 
> Dr Murray Jorgensen      http://www.stats.waikato.ac.nz/Staff/maj.html
> Department of Statistics, University of Waikato, Hamilton, New Zealand
> Email: maj at waikato.ac.nz                                Fax 7 838 4155
> Phone  +64 7 838 4773 wk    Home +64 7 825 0441    Mobile 021 1395 862
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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