2

I have a bunch of factor variables that have the same levels, and I want them all reordered similarly using fct_relevel from the forcats package. Many of the variable names start with the same characters ("Q11A" to "Q11X", "Q12A" to "Q12X", "Q13A" to "Q13X", etc.). I wanted to use the starts_with function from dplyr to shorten the task. The following error didn't give me an error, but it didn't do anything either. Is there anything I'm doing wrong?

library(dplyr)
library(purrr)
library(forcats)
library(tibble)

#Setting up dataframe
f1 <- factor(c("a", "b", "c", "d"))
f2 <- factor(c("a", "b", "c", "d"))
f3 <- factor(c("a", "b", "c", "d"))
f4 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, f2, f3, f4, f5)

levels(df$f1)
[1] "a" "b" "c" "d"

#Attempting to move level "c" up before "a" and "b".
df <- map_at(df, starts_with("f"), fct_relevel, "c")

levels(df$f1)
[1] "a" "b" "c" "d" #Didn't work

#If I just re-level for one variable:
fct_relevel(df$f1, "c")
[1] a b c d
Levels: c a b d
#That worked.
Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

3

I think you're looking for mutate_at:

df <- mutate_at(df, starts_with("f"), fct_relevel, ... = "c")

df$f1
[1] a b c d
Levels: c a b d
Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Evidently I'm confused as to when I should use `purrr::map` and when I should use `dplyr::mutate`. – Phil Jan 25 '17 at 19:35
  • 1
    That's easily forgiven. You usually want to use the different `mutate` variations for columns, and `map` within `mutate` for list columns and unvectorized calculations. – Axeman Jan 25 '17 at 19:38
  • @akrun, sorry I'm only finding decent dupes that end up using `mutate_each`, which is planned to be deprecated. Feel free to hammer if you have a good `mutate_at` target. – Axeman Jan 26 '17 at 09:25
  • It's okay. You may be right that it is difficult to find those with `mutate_at` – akrun Jan 26 '17 at 09:58