Jon Minton wrote: > Hi, > > I expect this is simple but haven’t found an answer looking on the > archives... > > I want to convert ‘NA’ (missing) to particular levels (nonmissing) in factor > vectors. > > e.g. I know > >> X <- c(1, 2, 3) > >> summary(X) > > Min. 1st Qu. Median Mean 3rd Qu. Max. > > 1.0 1.5 2.0 2.0 2.5 3.0 > >> X <- as.factor(X) > >> summary(X) > > 1 2 3 > > 1 1 1 > >> levels(X) > > [1] "1" "2" "3" > >> levels(X) <- c("A", NA, "B") > >> summary(X) > > A B NA's > > 1 1 1 > > But what if I want to turn the NA back into a level? > > How do I do this?
One way is to use recode() in the car package by John Fox. For example: library(car) X <- factor(c(1, NA, 3)) X [1] 1 <NA> 3 Levels: 1 3 recode(X, "NA='J'") [1] 1 J 3 Levels: 1 3 J > Thanks, Jon > > ------------------------------------------------------------------------ > ______________________________________________ > R-help@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. -- Chuck Cleland, Ph.D. NDRI, Inc. 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894 ______________________________________________ R-help@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.