Search code examples
rdplyrfactorsmutate

How to create factor with mutate with levels coming from another col


I have this df:

city code
PR 41
SC 42
RS 43

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))

Thanks!

EDIT: I don't want to do manually levels = c('PR', 'SC', 'RS') because it has many more categories!


Solution

  • 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 fct_reorder

    library(forcats)
    df <- df %>%
        mutate(city = fct_reorder(city, code))
    

    -checking

    levels(df$city)
    [1] "PR" "SC" "RS"
    

    data

    df <- structure(list(city = c("PR", "SC", "RS"), code = 41:43), 
    class = "data.frame", row.names = c(NA, 
    -3L))