我想在我的数据框中使用函数relevel()和reorder()。我知道relevel的工作原理,但我不明白为什么在我的数据框中看不到级别的变化。例如,假设我有鸢尾花数据集。
library(tidyverse)
head(iris)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 5.1 3.5 1.4 0.2 setosa
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa
iris$Species <- factor(iris$Species, levels = c("versicolor","setosa","virginica"),
labels = c("versicolor","setosa","virginica"))
由reprex包(v2.0.1)于2022-04-12创建
我可以使用这个函数来改变级别的顺序,或者在dplyr中使用这个函数:
iris %>%
mutate(Species=factor(Species)) %>%
mutate(Species=fct_relevel(Species,c("versicolor","setosa","virginica"))) %>%
head()
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 5.1 3.5 1.4 0.2 setosa
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa
由reprex package (v2.0.1)于2022-04-12创建 我的疑惑在于,尽管我在数据集中看到了级别的变化,但是当我调用数据集时,我并没有看到顺序的变化,而这对我来说至关重要。 这是我所看到的。
Species
setosa
...
versicolor
...
virginica
...
这就是我想要看到的
Species
versicolor
...
setosa
...
virginica
...
希望有人能提供帮助,使用Tidyverse改变顺序。
arrange
。我认为您只需要更改levels
。 - akrun