levels() with levels

Is there a function within forcats or elsewhere that returns the levels of a factor, but as a factor itself with the same levels? I find myself creating this function a fair bit - it's useful in combination with crossing(). Before adding it to my local package I was wondering if its equivalent exists already somewhere in the tidyverse or other common packages.

levels_w_levels <- function(x){
  factor(levels(x),levels = levels(x))
}

Doesn't unique() do this :question:

Mostly, but the vector it returns isn't sorted by the levels.

Ah yes, right you are.

How about sort(unique(f))?

Also, just discovered forcats::fct_unique(f)! Who kniew?

Perfect! That's what I was looking for, not sure why I couldn't find it. Also I tend to forget about sort() so thanks for the reminder.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.