将现有数据帧变量转换为 Tidyverse 中的因子

wyt*_*he4 3 r tidyverse

我知道这个问题有很多版本,但我正在寻找具体的解决方案。当dataframe中有一个现有的字符变量时,是否有一种简单的方法可以使用 tidyverse 格式将该变量转换为因子?例如,下面的第二行代码不会对因子级别重新排序,但最后一行会。我如何使第二行工作?在某些情况下这会很有用——导入和修改现有数据集。非常感谢!

df <- data.frame(x = c(1,2), y = c('post','pre')) %>%
      as_factor(y, levels = c('pre','post'))

df$y <- factor(df$y, levels = c('pre', 'post'))
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们可以使用fct_relevel来自forcats

library(dplyr)
library(forcats)
df1 <- data.frame(x = c(1,2), y = c('post','pre')) %>% 
       mutate(y = fct_relevel(y, 'pre', 'post')) 
Run Code Online (Sandbox Code Playgroud)

-输出

> df1$y
[1] post pre 
Levels: pre post
Run Code Online (Sandbox Code Playgroud)

关于 的使用as_factor,根据文档

与基本 R 相比,当 x 是字符时,此函数按照它们出现的顺序创建关卡,这在每个平台上都是相同的。

post,随后是pre

> as_factor(c('post','pre'))
[1] post pre 
Levels: post pre
Run Code Online (Sandbox Code Playgroud)

而以下选项将不起作用,因为没有指定levels参数as_factor

> as_factor(c('post','pre'), "pre", "post")
Error: 2 components of `...` were not used.

We detected these problematic arguments:
* `..1`
* `..2`

Did you misspecify an argument?
Run `rlang::last_error()` to see where the error occurred.
> as_factor(c('post','pre'), levels = c("pre", "post"))
Error: 1 components of `...` were not used.

We detected these problematic arguments:
* `levels`

Did you misspecify an argument?
Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)

另外,在 中,我们需要使用或tidyverse提取列,否则必须修改 中的列。pull.$mutate