【发布时间】:2021-11-07 16:45:46
【问题描述】:
如何按特定顺序设置级别?
所需的级别顺序是 - "CA", "IN", "FL" "NY"
library(dplyr)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states))
【问题讨论】:
如何按特定顺序设置级别?
所需的级别顺序是 - "CA", "IN", "FL" "NY"
library(dplyr)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states))
【问题讨论】:
使用levels = 参数。
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states, levels = c("CA", "IN", "FL", "NY"))
【讨论】:
您可以使用ordered 表示您想要一个有序因子:
states = ordered(c("FL", "NY", "CA", "IN"), levels = c("CA", "IN", "FL", "NY"))
str(states)
【讨论】:
我们可以使用来自forcats 包的fct_relevel:
library(dplyr)
library(forcats)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states)) %>%
mutate(states_fct = fct_relevel(states_fct, c("CA", "IN", "FL", "NY")))
levels(tbl$states_fct)
输出:
states states_fct
<chr> <fct>
1 FL FL
2 NY NY
3 CA CA
4 IN IN
> levels(tbl$states_fct)
[1] "CA" "IN" "FL" "NY"
【讨论】: