繁体   English   中英

无法使用 dplyr mutate() 和 recode_factor 重新编码因子的级别

[英]Failure to recode levels of a factor with dplyr mutate() and 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 级别的顺序,而不是级别。

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

> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM