[R] ifelse with a factor variable

Goran Brostrom gb at tal.stat.umu.se
Tue Oct 28 22:04:17 CET 2003


* Liaw, Andy <andy_liaw at merck.com> [2003-10-28 21:55]:
> Does the following help you?
> 
> > x <- factor(c("A", "B", NA))
> > levels(x) <- c(levels(x), "unknown")  # add an "unknown" level
> > x[is.na(x)] <- "unknown"  # change NAs to "unknown"
> > x
> [1] A       B       unknown
> Levels: A B unknown

Yes! Thank you,

Göran

> 
> Andy
> 
> > -----Original Message-----
> > From: Goran Brostrom [mailto:gb at tal.stat.umu.se] 
> > Sent: Tuesday, October 28, 2003 3:36 PM
> > To: r-help at stat.math.ethz.ch
> > Subject: [R] ifelse with a factor variable
> > 
> > 
> > 'ifelse' changes factors to character vectors (R-1.7.1, Linux):
> > 
> > > table(bal$soc.40)
> > 
> >           tax         noble semi-landless      landless       unknown 
> >          4035          5449         13342          9348             0 
> > 
> > 
> > > blah <- ifelse(is.na(bal$soc.40), "unknown", bal$soc.40)
> > > table(blah)
> > blah
> >       1       2       3       4 unknown 
> >    4035    5449   13342    9348    7970 
> > 
> > How do I get what I want (I mean: simply)? Upgrade to 1.8.0?
> > 
> > Göran
> > 
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list 
> > https://www.stat.math.ethz.ch/mailman/listinfo> /r-help
> > 
> 

-- 
 Göran Broström                    tel: +46 90 786 5223
 Department of Statistics          fax: +46 90 786 6614
 Umeå University                   http://www.stat.umu.se/egna/gb/
 SE-90187 Umeå, Sweden             e-mail: gb at stat.umu.se




More information about the R-help mailing list