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

时间:2017-01-25 18:56:49

标签: r dplyr purrr tidyverse

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

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 个答案:

答案 0 :(得分:2)

我认为您正在寻找mutate_at

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

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