[英]How to reorder a factor based on a subset (facets) of another variable, using forcats?
[英]Changing the factor level based on the value in a grouped variable using the dplyr and forcats packages
我正在嘗試根據來自另一個變量的某些值來更改因子的級別。 我將在一個例子中展示它。 我有一個這樣的表:
library(tidyverse)
set.seed(1)
df = tibble(
group = factor(rep(c("a", "b", "c", "d"), each = 5)),
x = c(rnorm(5, 0, 1), rnorm(5, 0, 2), rnorm(5, 0, 1.5), rnorm(5, 0, 3))
)
我想在變量x
的標准偏差的遞減值中更改group
因子的級別。
我設法得到它是這樣的:
lev = df %>% group_by(group) %>%
summarise(sd = sd(x)) %>%
arrange(desc(sd))
df = df %>% mutate(group = fct_relevel(group, as.character(lev$group)))
但是,我不喜歡這個解決方案,因為它需要創建一個輔助lev
表,我想避免這種情況。 有誰知道如何以dplyr
語義典型的更簡單和透明的方式實現這種效果。
您正在尋找的是forcats::fct_reorder()
:
df = df %>% mutate(group = fct_reorder(group, x, sd, .desc = TRUE))
df %>% group_by(group) %>% summarise(sd=sd(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.