无法使用dplyr mutate和recode_factor重新编码因子的水平

问题描述

我有

library(tidyverse)
mood <- 
  tibble(cond = factor(c('pl','nu','un')),rating = 1:3)

我想将情绪改变为:

moodWish <-
  tibble(cond = factor(c('P','N','U')),rating = 1:3)

我尝试过:

mood1 <- mood %>%
  mutate(cond = recode_factor(cond,'P' = 'pl','N' = 'nu','U' = 'un'))

我知道recode_factor在做某件事,因为它更改了cond级别的 order ,但是没有改变。

解决方法

“命名时,参数名称应该是要替换的当前值,参数值应该是新的(替换)值。”

> mood1 <- mood %>%
    mutate(cond = recode_factor(cond,'pl' = 'P','nu' = 'N','un' = 'U'))

> mood1
# A tibble: 3 x 2
  cond  rating
  <fct>  <int>
1 P          1
2 N          2
3 U          3