Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: argument in fct_recode to reorder based on sequence #45

Closed
rpodcast opened this issue Oct 17, 2016 · 4 comments
Closed

Comments

@rpodcast
Copy link

I struggled with making a clear title of this feature request, but here is my idea. I really like using the fct_recode function to change the levels of factors (especially for plotting purposes) but I noticed that the new version of the factor keeps the same order of levels as the original version before the recoding using fct_recode even though I specified the order different in the arguments to fct_recode. It would be nice to have an extra parameter in fct_recode to let the order be dictated by how the levels are given in the call. Here's a minimal example using the forcats CRAN release of 0.1.1:

library(forcats)
data(diamonds)

# show order of cut
levels(diamonds$cut)
# [1] "Fair"      "Good"      "Very Good" "Premium"   "Ideal"  

# recode levels using fct_recode
diamonds2 <- diamonds %>%
  mutate(cut2 = fct_recode(cut, "Very Great" = "Very Good", "Great" = "Good", "Really Ideal" = "Ideal", "Really Premium" = "Premium", "Bad" = "Fair"))

# show order of cut2
levels(diamonds2$cut2)
# [1] "Bad"            "Great"          "Very Great"     "Really Premium" "Really Ideal"  
@krlmlr
Copy link
Member

krlmlr commented Nov 14, 2016

Does fct_rev() and/or fct_relevel() work for you?

@hadley hadley closed this as completed Dec 30, 2016
@epruesse
Copy link

Just ran into the same issue. I've got some data with nonsensically named classes and want to impose both new names and a sensible order at the same time.

Since google led me here ... could you briefly explain a good way to do that? I.e. have a fct_recode that also relevels the factor in order of the arguments provided?

@epruesse
Copy link

In answer to myself:

fct_reorg <- function(fac, ...) {
  fct_recode(fct_relevel(fac, ...), ...)
}

Works like this:

> x<-factor(c("a","b","c"))
> x
[1] a b c
Levels: a b c
> fct_recode(x, B="b", C="c")
[1] a B C
Levels: a B C
> fct_reorg(x, B="b", C="c")
[1] a B C
Levels: B C a

@sjackman
Copy link

I ran into this same question recently.

relevel = c(
  "Alfa" = "A",
  "Bravo" = "B",
  "Charlie" = "C",
  "Delta" = "D")

after <- before %>%
  mutate(
    Var1 = fct_recode(fct_relevel(Var1, !!!relevel), !!!relevel),
    Var2 = fct_recode(fct_relevel(Var2, !!!relevel), !!!relevel))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants