How to reverse a factor using base in a tidyeval function?

Hi,

I have a forcats dependency in a package I author due to the use of fct_rev.

I would like to replace this using base code. However, the base version of reversing levels doesn't seem to work as expected in a tidyeval function??

I would like to make the reverse_levels function below work in tidyeval code without using fct_rev.

Thanks!

library(palmerpenguins)
library(tidyverse)

penguins |>
  mutate(species = factor(species, levels = rev(levels(species)))) |>
  pull(species) |>
  levels()
#> [1] "Gentoo"    "Chinstrap" "Adelie"

reverse_levels <- function(data, x) {

  data |>
    mutate(x = factor({{x}}, levels = rev(levels({{ x }})))) |>
    pull( {{ x }}) |>
    levels()
}

reverse_levels(penguins, species)
#> [1] "Adelie"    "Chinstrap" "Gentoo"

Created on 2024-02-07 with reprex v2.1.0

This approach first reverses the order of the factor levels using rev and then recreates the factor with the reversed order using factor .

1 Like

Aha! Thanks

Know how to create the reverse levels function correctly?

your reverse_levels fuction put the result of reversing the factor levels into a column called exactly x (not species) but then looked at the original species column to inspect the ordering there, which was unchanged.
therefore change

mutate(x = 

to

mutate( {{x}} := 

note the use of walrus operator :=

1 Like

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.