0

In my data frame (df), there is a column in my data set called "Subcategory". It returns all the values which are indented

Advertising and Marketing

  • TV Ads
  • Website Ads
  • Radio Ads

Employee Benefits

  • Retirement
  • Team Building
  • Medical Insurance

Insurance

  • Legal Insurance
  • Business Insurance
  • Rental Insurance

All together there are 46 subcategories that are supposed to be assigned to 12 main categories. What's the quickest way in R to assign and match these subcategories to a new column called Category with the appropriate matching?

Chives M
  • 15
  • 3
  • Create a look up table with columns for main category, subcategory then merge that (with `base::merge` or `dplyr::left_join` to add the info to your main table. It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 08 '22 at 15:16

1 Answers1

0
library(dplyr)

df <- df %>%
  mutate(Category = case_when(
    Subcategory %in% c("TV Ads","Website Ads","Radio Ads") ~ "Advertising and Marketing",
    Subcategory %in% c("Retirement","Team Building","Medical Insurance") ~ "Employee Benefits"
  ))
Eric
  • 1,381
  • 9
  • 24