簡體   English   中英

使用 dplyr 和 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM