-1

I have read the SO thread: Reorder levels of a factor without changing order of values, which works fine. However, on the particular use case, I am puzzled on the output:

> df$mode
[1]  write               read                write_with_journal  write               read                write_with_journal
[7]  write               read                write_with_journal
Levels:  read  write  write_with_journal

Now, I am changing the factor order from "read write write_with_journal" to "write read write_with_journal":

> factor(df$mode, levels = c('write', 'read', 'write_with_journal'))
[1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
Levels: write read write_with_journal

Notice all the previous category values "write", "read" etc. are replaced with NA. I am not sure why this is happening. If I manually create the data frame (instead of reading from a file) as the following:

> p = factor(rep(c("write", "read", "write_with_journal"),3))
> factor(p, levels = c('write', 'read', 'write_with_journal'))

Then everything is fine. Why?

Community
  • 1
  • 1
Oliver
  • 3,592
  • 8
  • 34
  • 37
  • Try `factor(as.character(df$mode), levels = c('write', 'read', 'write_with_journal'))`. – Roland Aug 22 '13 at 20:15
  • Not sure why this question is down flagged. I'd appreciate it if you care to explain so I could improve future questions. Thx – Oliver Aug 22 '13 at 21:04

1 Answers1

1

You probably have training spaces in all the factor levels. Do this:

df$mode <- factor( gsub(" ", "", df$mode), 
                   levels = c('write', 'read', 'write_with_journal'))

Alternately (but not correcting the problem) you could do this:

df$mode <- factor( df$mode, 
                   levels = levels(df$mode)[c(2,1,3)] )

Just to demonstrate this is plausible (although by no means definitely the problem since other none printing characters do exist):

> p = factor(rep(c("write ", "read ", "write_with_journal "),3))
>  factor(p, levels = c('write', 'read', 'write_with_journal'))
[1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
Levels: write read write_with_journal
IRTFM
  • 258,963
  • 21
  • 364
  • 487