I'm trying to rename the levels in a factor. I have a level "Very long text that needs to be shortened." and want to change its name to "Levelname". However, when I try:
levels(df$varname) ["Very long text that needs to be shortened."] <- "Levelname"
All that happens is that level Levelname
that only has missing values is generated while Very long text...
level continues to exist.
I can still rename the level using
levels(df$varname) [1] <- "Levelname
But would rather avoid it in case level numbers somehow change when I rerun the code. (I don't know if that would ever actually happen, but better safe than sorry.)
How can I rename the level and make sure the right level has its name changed?
The problem is that the levels aren't named, so you can't reference them that way. If you want a safe way to manipulate factor levels, look at the forcats
package (part of tidyverse
). That has the function fct_recode
which will do what you want.
library(forcats)
df$varname <- fct_recode(df$varname, Levelname = "Very long text that needs to be shortened")