Home > OS >  Rename multiple values of a variable into the same category within a new variable in R
Rename multiple values of a variable into the same category within a new variable in R

Time:07-21

I need to rename multiple values of a variable into categories within a new variable in R. Is there a more efficient way to do this rather than rename every single one individually? Here is the code I have so far

data.set %>% mutate(income = recode(country, "USA" = "HIC", "Canada" = "HIC", "Japan" = "HIC", "India" = "LMIC"))

Currently the data looks like this, and I want to create the income variable

ID           countries        **income**
1            USA                 HIC
2            Canada              HIC
3            Japan               HIC
4            USA                 HIC
5            India               LMIC

CodePudding user response:

Recode is a simpler version of case_when, so we can just use case_when.

df %>%
  mutate(income = case_when(
    countries %in% c("USA", "Canada", "Japan") ~ "HIC",
    countries %in% c("India") ~ "LMIC",
    TRUE ~ NA_character_
  ))
  •  Tags:  
  • r
  • Related