Using fct_relevel over a list of variables using m

2019-07-19 04:01发布

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.

1条回答
迷人小祖宗
2楼-- · 2019-07-19 04:16

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
查看更多
登录 后发表回答