使用 map_at 在变量列表上使用 fct_relevel

Using fct_relevel over a list of variables using map_at

我有一堆具有相同水平的因子变量,我希望使用 forcats 包中的 fct_relevel 对它们进行类似的重新排序。许多变量名称以相同的字符开头("Q11A" 到 "Q11X"、"Q12A" 到 "Q12X"、"Q13A" 到 "Q13X" 等) .我想使用 dplyr 中的 starts_with 函数来缩短任务。下面的错误并没有给我报错,但也没有做任何事情。我做错了什么吗?

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.

我想你在找 mutate_at:

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

df$f1
[1] a b c d
Levels: c a b d