正在更新 fct_relevel 解决方案,因为 across 接管了 mutate_at
Updating fct_relevel solution since across took over mutate_at
的解决方案不再有效,因为 mutate_at 已被弃用。我很难使用 mutate(across(...), fct_relevel(., ....)
拼凑更新的解决方案,因为我收到一个错误
"Problem with `mutate()` input `..2`.
i `..2 = ~...`.
x `..2` must be a vector, not a `formula` object."
但是没有公式
假设我有
f1 <- factor(c("a", "b", "c", "d"))
g2 <- factor(c("a", "b", "c", "d"))
t3 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("m", "l", "f", "p"))
y8 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, g2, t3, f5, y8)
并且我想要 fct_relevel
f1、g2 和 y8(非顺序变量)以便您将因子排序为“c”、“d”、“b”、“a”对于所有这三个变量。
大概是这样的:
library(dplyr) # 1.0.7
library(forcats) # 0.5.1
f1 <- factor(c("a", "b", "c", "d"))
g2 <- factor(c("a", "b", "c", "d"))
t3 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("m", "l", "f", "p"))
y8 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, g2, t3, f5, y8)
df_1 <- df %>%
mutate(across(c(f1, g2, y8), forcats::fct_relevel, "c", "d", "b", "a"))
levels(df$f1)
#> [1] "c" "d" "b" "a"
levels(df$g2)
#> [1] "c" "d" "b" "a"
levels(df$t3)
#> [1] "a" "b" "c" "d"
levels(df$f5)
#> [1] "f" "l" "m" "p"
levels(df$y8)
#> [1] "c" "d" "b" "a"
由 reprex package (v2.0.0)
于 2021-07-25 创建
下面我再添加两个等同于上面的语法。
# option 2
df_2 <- df %>%
mutate(across(c(f1, g2, y8), ~forcats::fct_relevel(., "c", "d", "b", "a")))
# option 3
df_3 <- df %>%
mutate(across(c(f1, g2, y8), ~forcats::fct_relevel(.x, "c", "d", "b", "a")))
identical(df_1, df_2) # TRUE
identical(df_1, df_3) # TRUE
上述fct_relevel()
的操作方式是将每一列(即f1
、g2
、y8
)视为传递给[=16的向量=],而不是 .
或 .x
。它“知道”做这样的“堵塞”,因为我们在函数之前使用 ~
。
mutate(across(...), fct_relevel(., ....)
拼凑更新的解决方案,因为我收到一个错误
"Problem with `mutate()` input `..2`.
i `..2 = ~...`.
x `..2` must be a vector, not a `formula` object."
但是没有公式
假设我有
f1 <- factor(c("a", "b", "c", "d"))
g2 <- factor(c("a", "b", "c", "d"))
t3 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("m", "l", "f", "p"))
y8 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, g2, t3, f5, y8)
并且我想要 fct_relevel
f1、g2 和 y8(非顺序变量)以便您将因子排序为“c”、“d”、“b”、“a”对于所有这三个变量。
大概是这样的:
library(dplyr) # 1.0.7
library(forcats) # 0.5.1
f1 <- factor(c("a", "b", "c", "d"))
g2 <- factor(c("a", "b", "c", "d"))
t3 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("m", "l", "f", "p"))
y8 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, g2, t3, f5, y8)
df_1 <- df %>%
mutate(across(c(f1, g2, y8), forcats::fct_relevel, "c", "d", "b", "a"))
levels(df$f1)
#> [1] "c" "d" "b" "a"
levels(df$g2)
#> [1] "c" "d" "b" "a"
levels(df$t3)
#> [1] "a" "b" "c" "d"
levels(df$f5)
#> [1] "f" "l" "m" "p"
levels(df$y8)
#> [1] "c" "d" "b" "a"
由 reprex package (v2.0.0)
于 2021-07-25 创建下面我再添加两个等同于上面的语法。
# option 2
df_2 <- df %>%
mutate(across(c(f1, g2, y8), ~forcats::fct_relevel(., "c", "d", "b", "a")))
# option 3
df_3 <- df %>%
mutate(across(c(f1, g2, y8), ~forcats::fct_relevel(.x, "c", "d", "b", "a")))
identical(df_1, df_2) # TRUE
identical(df_1, df_3) # TRUE
上述fct_relevel()
的操作方式是将每一列(即f1
、g2
、y8
)视为传递给[=16的向量=],而不是 .
或 .x
。它“知道”做这样的“堵塞”,因为我们在函数之前使用 ~
。