I have this df:
I want to change city to factor, but keep the order as in the code. If I only do
df %>% mutate(city= factor(city))
it orders alphabetically.
I would like something such as
df %>% mutate(city= factor(city, levels = code))
EDIT: I don’t want to do manually
levels = c('PR', 'SC', 'RS') because it has many more categories!
We may use
levels = unique(city)) as
unique gets the unique elements in the order of occurrence of the elements
library(dplyr) df <- df %>% mutate(city = factor(city, levels = unique(city)))
If we want to reorder based on a different column, use
library(forcats) df <- df %>% mutate(city = fct_reorder(city, code))
levels(df$city)  "PR" "SC" "RS"
df <- structure(list(city = c("PR", "SC", "RS"), code = 41:43), class = "data.frame", row.names = c(NA, -3L))