2
votes

How do you relevel a factor with dplyr and mixedsort in the same pipe?

df %>%
     relevel(.$var, mixedsort(levels(.$var)))

Results in error message "'relevel' only for (unordered) factors" even though var is a factor. I have also tried using the magrittr pipe and the relevel(var, mixedsort(levels(var))) but to no avail.

I guess this could all be done by saving mixedsort(levels(var)) and then calling it from within the relevel function but I would like to do it all in one relevel call if possible.

1
wrap with {} around it - akrun

1 Answers

1
votes

We can wrap with {}, however, the relevel ref takes only a single element

library(dplyr)
library(gtools)
iris %>% 
     {relevel(.$Species, mixedsort(levels(.$Species))[1])}

Or change the order of levels, apply factor

iris %>%
     {factor(.$Species, levels = mixedsort(levels(.$Species)))}

If we want to reorder, another option is fct_relevel

library(forcats)
iris %>%
    {fct_relevel(.$Species, mixedsort(levels(.$Species)))}

Or as we are using dplyr, do that in mutate or transmute and then pull (transmute if only a single column is required and then want to pull as a `vector)

iris %>%
   transmute(Species = factor(Species, levels = mixedsort(levels(Species)))) %>%
   pull(Species)

If we need the full set of columns, use mutate

iris1 <- iris %>%
   mutate(Species = factor(Species, levels = mixedsort(levels(Species))))