[R] renaming factor-labels / add factors etc.

Peter Alspach PAlspach at hortresearch.co.nz
Tue Dec 16 04:15:03 CET 2008


Jörg

To add a level you could:

x <- factor(c("xyz1", "abc1", "xyz2", "abc2"))
x1 <- factor(x, levels=c(levels(x), 'fgh'))
summary(x)
abc1 abc2 xyz1 xyz2 
   1    1    1    1 
summary(x1)
abc1 abc2 xyz1 xyz2  fgh 
   1    1    1    1    0 

For the others, I tend to convert to a character, make the changes and convert back to a factor - but there is probably a better way.

HTH ....

Peter Alspach.

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Jörg Groß
> Sent: Tuesday, 16 December 2008 3:26 p.m.
> To: r-help at r-project.org
> Subject: [R] renaming factor-labels / add factors etc.
> 
> Hi,
> 
> how can I change a defined factor-variable?
> Like adding levels, renaming existing levels or merge several 
> levels of a factor to one level?
> 
> 
> 
> For example; following factor-variable is given:
> 
>   x <- factor(c("xyz1", "abc1", "xyz2", "abc2"))
> 
> 
> How can I add the level fgh?
> And how can I merge "xyz1" and "xyz2" to one level?
> And how can I change the name?
> 
> 
> 
> 
> Thanks for any help!
> 
> ______________________________________________
> 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.
> 

The contents of this e-mail are confidential and may be subject to legal privilege.
 If you are not the intended recipient you must not use, disseminate, distribute or
 reproduce all or any part of this e-mail or attachments.  If you have received this
 e-mail in error, please notify the sender and delete all material pertaining to this
 e-mail.  Any opinion or views expressed in this e-mail are those of the individual
 sender and may not represent those of The New Zealand Institute for Plant and
 Food Research Limited.



More information about the R-help mailing list