Skip to content
Prev 78969 / 398502 Next

Removing and restoring factor levels (TYPO CORRECTED)

On 10/13/2005 1:07 PM, Marc Schwartz (via MN) wrote:
That one doesn't work.  What "factor(x, levels=levels(master))" says is 
to convert x to a factor, coding the values in it according the levels 
in master.  But at this point x has values which are integers, so  they 
won't match the levels of master, which are probably character strings.

For example:

 > master <- factor(letters)
 > print(x <- factor(letters[1:3]))
[1] a b c
Levels: a b c
 > print(x <- as.integer( factor(x, levels = levels(master) ) ) )
[1] 1 2 3
 > print(x <- factor(x, levels = levels(master)))
[1] <NA> <NA> <NA>
Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z

I get NA's at the end because the values 1,2,3 aren't in the vector of 
factor levels (which are the lowercase letters).

Duncan Murdoch