mk9y
mk9y

Reputation: 390

Failure to recode levels of a factor with dplyr mutate() and recode_factor

I have:

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

I would like to mutate mood into:

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

I tried:

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

I know that recode_factor is doing something, because it changes the order of the levels of cond but not the levels.

Upvotes: 0

Views: 662

Answers (1)

BellmanEqn
BellmanEqn

Reputation: 789

"When named, the argument names should be the current values to be replaced, and the argument values should be the new (replacement) values."

> 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

Upvotes: 1

Related Questions