0

I have a variable that looks like this:

> levels(Cambodia$`Income changed after 2020`)
[1] "Yes, I lost a total of income"        "Yes, I lost a partial of income"      "No, I earn the same amount of income"
[4] "Yes, I earn more income" 

I want to combine "Yes, I earn more income" and "No, I earn the same amount of income" to form a new level in the variable, so that it would look like:

> levels(Cambodia$`Income changed after 2020`)
[1] "Yes, I lost a total of income"        "Yes, I lost a partial of income"      "No income loss" 

I tried doing this but it did not work:

library(forcats)
Cambodia %>% fct_collapse(Cambodia$`Income changed after 2020` == c("Yes, I earn more income","No, I earn the same amount of income"))
Natasha H
  • 59
  • 7
  • Your `fct_collapse` line didn't work because you passed what seems to be a data frame (can't tell without any of your data) to a function that expects a vector, and then tried to create a level with the name "Cambodia$`Income changed after 2020`", which doesn't make a lot of sense, and used a comparison (`==`) instead of an assignment (`=`). I'd recommend reading through the docs of functions like this first to see how they're used – camille Jan 27 '22 at 19:01
  • Does this answer your question? https://stackoverflow.com/questions/19410108/cleaning-up-factor-levels-collapsing-multiple-levels-labels – Anil Jan 27 '22 at 19:02

1 Answers1

0

Figured it out:

levels(Cambodia$`Income changed after 2020`)[levels(Cambodia$`Income changed after 2020`)%in%c("Yes, I earn more income","No, I earn the same amount of income")] <- "no income change"
Natasha H
  • 59
  • 7