Dear All, I wonder how to re-code a categorical variable without using the ifelse loops. For example: Let X be a categorical variable with 6 levels, levels(X) = c(1,2,3,4,5,6) How to create a new categorical variable Y with levels, 10,11,12, say , such that: Y = 10 if X =1 or X=2 Y = 11 if X =3 or 4 Y =11 if X = 5 or 6 many thanks, Bernard --------------------------------- [[alternative HTML version deleted]]
Look at function recode() in library("car"). -Christos -----Original Message----- From: r-help-bounces at stat.math.ethz.ch [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Marc Bernard Sent: Thursday, February 02, 2006 11:12 AM To: r-help at stat.math.ethz.ch Subject: [R] re-coding variables Dear All, I wonder how to re-code a categorical variable without using the ifelse loops. For example: Let X be a categorical variable with 6 levels, levels(X) = c(1,2,3,4,5,6) How to create a new categorical variable Y with levels, 10,11,12, say , such that: Y = 10 if X =1 or X=2 Y = 11 if X =3 or 4 Y =11 if X = 5 or 6 many thanks, Bernard --------------------------------- [[alternative HTML version deleted]] ______________________________________________ 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
Marc Bernard <bernarduse1 at yahoo.fr> writes:> Dear All, > > I wonder how to re-code a categorical variable without using the ifelse loops. For example:(What's an "ifelse loop"???)> Let X be a categorical variable with 6 levels, levels(X) = c(1,2,3,4,5,6) > > How to create a new categorical variable Y with levels, 10,11,12, say , such that: > Y = 10 if X =1 or X=2 > Y = 11 if X =3 or 4 > Y =11 if X = 5 or 6One way is the recode() function in the car package. Another is Y <- X levels(Y) <- c(10,10,11,11,12,12) or levels(Y) <- list("10"=c(1,2),"11"=c(3,4),"12"=c(5,6)) and a 4th one could be Y <- factor(c(10,10,11,11,12,12)[X]) (which may need a safeguarding "levels=c(10,11,12)" in case not all levels are present). -- O__ ---- Peter Dalgaard ??ster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907