簡體   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