0

My variable "Satisfaction" has levels 1, 2, 3, 4.

I want to combine 3,4 to create a new level: "0"; and 1,2 to create new level: "1"

I have done this:

combineLevels(EB734_May_2010$Satisfaction, levs = c("3","4"), newLabel =("0"))

After running the above code, I ran the levels function again, but still got 1,2,3,4. Is there anything I'm doing wrong?

Thanks

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51

2 Answers2

2
forcats::fct_recode(
  EB734_May_2010$Satisfaction, 
  "0" = "3", "0" = "4", "1" = "1", "1" = "2"
)
det
  • 5,013
  • 1
  • 8
  • 16
2

By a base solution, you can assign a named list to the levels of a factor object.

x <- factor(rep(1:4, each = 2))

# [1] 1 1 2 2 3 3 4 4
# Levels: 1 2 3 4

levels(x) <- list("0" = c(3, 4), "1" = c(1, 2))
x

# [1] 1 1 1 1 0 0 0 0
# Levels: 0 1

Or using recode() from dplyr:

dplyr::recode(x, "1" = "1", "2" = "1", "3" = "0", "4" = "0")

# [1] 1 1 1 1 0 0 0 0
# Levels: 1 0

It can also use a named character vector to recode factors with unquote splicing.

dplyr::recode_factor(x, !!!setNames(c(1, 1, 0, 0), levels(x)))

# [1] 1 1 1 1 0 0 0 0
# Levels: 1 0
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51