将 fct_relevel 与 fct_expand 组合以创建具有空因子水平的因子顺序

问题描述 投票:0回答:1

我有一个数据集,现在不包含但后来包含定义的顺序。

比如说

library(tidyverse)

x <- c("a")

fct_relevel("d", c("a", "b", "c", "d"))
[1] d
Levels: d
Warning message:
3 unknown levels in `f`: a, b, and c

fct_expand("d", c("a", "b", "c", "d"))
[1] d
Levels: d a b c

如何使用

fct_relevel()
fct_expand()
来预先定义级别“a b c d”的顺序,即使当前级别未知? (另一个
dplyr
解决方案也可以)

非常感谢!

r tidyverse forcats
1个回答
0
投票

如果您正在使用 tibbles,则可以使用

complete
:

aux <- tibble(x = fct("a", c("a", "b", "c", "d")))
new_aux <- complete(aux, x = levels(x))

> aux
# A tibble: 1 × 1
  x    
  <fct>
1 a 

> new_aux
# A tibble: 4 × 1
  x    
  <chr>
1 a    
2 b    
3 c    
4 d
© www.soinside.com 2019 - 2024. All rights reserved.