2

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

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.
4

1 回答 1

3

我想你正在寻找mutate_at

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

df$f1
[1] a b c d
Levels: c a b d
于 2017-01-25T19:19:16.183 回答