在 R 中使用 tidyverse 重新调整因子和重新排序因子 [英] relevel factors and reorder factors using tidyverse in R

查看:20
本文介绍了在 R 中使用 tidyverse 重新调整因子和重新排序因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的数据框中使用 relevel()reorder() 函数.我了解 relevel 的工作原理,但我不明白为什么我看不到 data.frame 中级别的变化.例如,假设我有 iris 数据集

I want to use the functions relevel() and reorder() in my data frame. I understand how relevel works but I do not understand why I do not see the change of the levels in my data.frame. For example imagine that I have the iris dataset

iris
iris$Species <- factor(iris$Species, levels = c("versicolor","setosa","virginica"), 
                       labels = c("versicolor","setosa","virginica"))

我可以使用这个函数来改变关卡的顺序或者 dplyr 中的这个函数:

I can use this function to change the order of the levels or this function in dplyr :

iris %>% 
  mutate(Species=factor(Species)) %>% 
  mutate(Species=fct_relevel(Species,c("versicolor","setosa","virginica")))

我不明白的是,虽然我看到我的数据集中的级别发生了变化,但当我调用我的数据集时,我没有看到订单的变化,这对我来说是必不可少的.这是我看到的

What i do not get is that while i see the change in the levels in my data set, when i call my data set i do not see the change of the order and this is essential to me. This is what i see

Species
setosa
...
versicolor
...
virginica
...

这就是我想看到的

Species
versicolor
...
setosa
...
virginica
...

对于实际使用 tidyverse 更改顺序的任何帮助表示赞赏.

Any help to actually change the order with tidyverse is appreciated.

推荐答案

我们需要赋值回原数据进行修改.除了改变levels的顺序,如果行顺序也需要改变,我们可能需要arrange数据

We need to assign back to make the changes in the original data. In addition to changing the order of levels, we may need to arrange the data if the rows order needs to be changed as well

iris <- iris %>% 
  mutate(Species=factor(Species)) %>% 
  mutate(Species=fct_relevel(Species,c("versicolor","setosa","virginica"))) %>%
 arrange(Species)


或者可以使用 magrittr

library(magrittr)
iris %<>% 
  mutate(Species=factor(Species)) %<>% 
  mutate(Species=fct_relevel(Species,c("versicolor","setosa","virginica")))%>%
  arrange(Species)

检查级别

levels(iris$Species)
[1] "versicolor" "setosa"     "virginica" 

这篇关于在 R 中使用 tidyverse 重新调整因子和重新排序因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆