开始使用免费开始使用

fct_relevel() 的妙用

在上一个练习中,必须写出每个水平的名称来显式重新排序因子。但有时水平很多,而您只需要移动其中一个。为了避免把所有水平都写一遍,您可以在 fct_relevel() 中使用一些辅助参数,减少输入量。让我们在 multiple_choice_responses 中的变量 FormalEducation 上试试这些用法;先在控制台查看 multiple_choice_responses$FormalEducation 的各个水平以开始。

本练习是课程的一部分

Tidyverse 中的分类数据

查看课程

练习说明

  • 通过三次 mutate 调用,将 FormalEducation 作如下调整:
    • 将 "I did not complete any formal education past high school" 和 "Some college/university study without earning a bachelor's degree" 移到最前面。
    • 将 "I prefer not to answer" 移到最后一个水平。
    • 将 "Doctoral degree" 移到第 6 个水平(也就是排在第 5 个水平之后)。

交互式实操练习

通过完成这段示例代码来试试这个练习。

multiple_choice_responses %>%
    # Move "I did not complete any formal education past high school" and "Some college/university study without earning a bachelor's degree" to the front
    mutate(FormalEducation = fct_relevel(FormalEducation, ___, "Some college/university study without earning a bachelor's degree")) %>%
    # Move "I prefer not to answer" to be the last level.
    mutate(FormalEducation = fct_relevel(FormalEducation, ___, after = Inf)) %>%
    # Move "Doctoral degree" to be after the 5th level
    mutate(FormalEducation = fct_relevel(FormalEducation, ___, ____)) %>%
    # Examine the new level order
    pull(FormalEducation) %>%
    levels()
编辑并运行代码