我有一个数据集,现在不包含但后来包含定义的顺序。
比如说
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
解决方案也可以)
非常感谢!
如果您正在使用 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