我经常制作一个因子变量,我想保留它来自的变量的顺序。我觉得我应该能够通过在新分类变量的每组中取平均值,然后将其用作 fct_reorder 中的排序变量来做到这一点,但它似乎不起作用。这是一个简单的例子:
library(tidyverse)
test_data <- mtcars %>%
mutate(mpg_cat=case_when(mpg>20 ~ "More than 20",
mpg<=20 & mpg>=15 ~ "15-20",
mpg<15 ~ "Less than 15")) %>%
group_by(mpg_cat) %>%
mutate(avg_mpg=mean(mpg),
mpg_cat=fct_reorder(mpg_cat,avg_mpg))
levels(test_data$mpg_cat) #Want the order to be less than 15, 15-20, More than 20
最佳答案
您可以修改您的管道以根据您创建的均值变量对其进行排序,并基于该变量设置排序因子水平:
library(dplyr)
test_data <- mtcars |>
mutate(
mpg_cat = case_when(
mpg > 20 ~ "More than 20",
mpg <= 20 & mpg >= 15 ~ "15-20",
mpg < 15 ~ "Less than 15"
)
) |>
group_by(mpg_cat) |>
mutate(avg_mpg = mean(mpg)) |>
ungroup() %>%
arrange(avg_mpg) |>
mutate(
mpg_cat = factor(
mpg_cat,
levels = unique(mpg_cat),
ordered = TRUE
)
)
head(test_data$mpg_cat)
# [1] Less than 15 Less than 15 Less than 15 Less than 15 Less than 15 15-20
# Levels: Less than 15 < 15-20 < More than 20
或者,如果您纯粹为了顺序创建均值,则可以跳过所有分组,创建一个新变量并通过在开始时按 mpg
排序取消分组,这确保了 unique (mpg_cat)
是正确的顺序。
mtcars |>
arrange(mpg) |>
mutate(
mpg_cat = case_when(
mpg > 20 ~ "More than 20",
mpg <= 20 & mpg >= 15 ~ "15-20",
mpg < 15 ~ "Less than 15"
)
) |>
mutate(
mpg_cat = factor(
mpg_cat,
levels = unique(mpg_cat),
ordered = TRUE
)
)
关于根据组平均值重新排序因子水平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74061305/