Search code examples
rdplyrforcats

How to use fct_relevel with mutate_at syntax


I want to relevel the factors in a dataset, however I'm really struggling with the fct_relevel syntax and using it with mutate_at. I get a series of errors about my data not being a factor.

The solution must allow me to relevel multiple factors (the actual dataset has 20-odd factors to relevel in different ways)

This answer seems like it should work, but I'm clearly not picking up the syntax properly. Where am I going wrong?

Here's an example:

library(tidyverse)

dat <- tibble (x1 = c("b", "b", "a", "c", "b"),
               x2 = c("c", "b", "c", "a", "a"),
               y = c(10, 5, 12, 3, 4)) %>% 
  mutate_at(.vars = vars(x1:x2), factor)

I'm definitely dealing with factors

sapply(dat, class)

But I can't relevel x1, I receive the following error: f must be a factor (or character vector))

dat %>% fct_relevel(x1, "c", "b", "a")

And this is what I ideally want to be able to do

dat2 <- dat %>% 
  mutate_at(.vars = vars (x1:x2),
            .funs = fct_relevel("c", "b", "a"))

At the moment that final set is giving me the following errors:

Error: Can't create call to non-callable object

Call rlang::last_error() to see a backtrace

In addition: Warning message:

Unknown levels in f: b, a

I'd be really grateful for anyone pointing out what I'm sure is an obvious mistake.


Solution

  • This should work

    library(dplyr)                     
    library(forcats)
    
    dat <- dat %>% mutate_at(vars(x1:x2), ~fct_relevel(., c("c", "b", "a")))
    
    dat$x1
    #[1] b b a c b
    #Levels: c b a
    dat$x2
    #[1] c b c a a
    #Levels: c b a