Factors and levels #
If you’re not careful you can just rename the levels of a factor rather than reordering them #
I did:
levels(df$factor) <- levels(df$factor)[c(5,4,1,3,2)]
or similar and then continued merrily on with my analysis. You can even check to see that your “reordering” has worked!:
levels(df$factor)
Everything looks fine and the levels are in the right order! Except… you haven’t actually reordered the levels. It just looks like you have. You have actually just re-allocated the names of the levels. And your survey data that was originally tagged “Very unhappy” might now be tagged “Very happy”…
How to do it properly #
df$factor <- factor(df$factor, levels(df$factor)[c(5,4,3,2,1)])
Subtle difference… but rather important!
PS
A perhaps better way of doing it is:
opinion_levels <- c(
"Really unhappy",
"Slightly unhappy",
"Neutral",
"Slightly happy",
"Really happy")
phe_data_opinions$channel_switch_sentiment <- factor(phe_data_opinions$channel_switch_sentiment,
levels = opinion_levels)
You then have opinion_levels as an object to use again if you need it.
Then wondering if
phe_data_opinions$channel_switch_sentiment %<>% factor(.,
levels = opinion_levels)
might work as a slightly more concise version of the above? Using {magrittr}’s assignment pipe (lightbulb moment!)