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.
I think you're looking for
mutate_at
: