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?