Parseltongue
Parseltongue

Reputation: 11697

Relevel every factor at once in dplyr chain

I want all factors that have the underscore "_importance" to be releveled in the following order: "Don't care at all" , "Care a little", "Care somewhat", "Care somewhat strongly", "Care Strongly"

I'm currently doing the following to convert from character to factor classes, but cannot figure out how to relevel within a pipe:

test <- test %>%
  select(contains("_importance")) %>%
  mutate_if(is.character, as.factor)

Upvotes: 1

Views: 1002

Answers (1)

lroha
lroha

Reputation: 34601

You can use fct_relevel from forcats.

library(forcats)
library(dplyr)

neworder <- c("Don't care at all" , "Care a little", "Care somewhat", "Care somewhat strongly", "Care Strongly")

test  %>% 
  mutate_at(vars(contains("_importance")), ~fct_relevel(.x, neworder))

Note that fct_relevel can also apply functions on the current factor levels, so if, for example, you just wanted to reverse the current levels you could do fct_relevel(f, rev)

Upvotes: 1

Related Questions