lundi 8 février 2021

Conditionally replace variable with different variable

I haven't been able to find a thread similar to this question, so apologies if it's been asked already.

I am trying to: conditionally replace values of a character variable ("JobCategory_1") with the values in character variable ("JobCategory_2") to create my new variable ("My_Category").

I have data which looks like:

obs  JobCategory_1                 JobCategory_2      My_Category
1    Business and Administration   Social Sciences     
2    Research and Development      NA
3    Accounting and Finance        Health
4    Admin                         NA
5    Customer Service              Banking
6    Accounting and Finance        Health
7    Languages                     Education

I have a list of jobs in which I'm interested in changing:

NotSectors <- c("Business and Administration", 
                "Business Development", 
                "Consultancy and Training", 
                "Customer Service", 
                "Development and Project Management", 
                "Economics")

I hope to get something like:

obs  JobCategory_1                 JobCategory_2      My_Category
1    Business and Administration   Social Sciences    Social Sciences 
2    Research and Development      NA                 Research and Development
3    Accounting and Finance        Health             Accounting and Finance
4    Admin                         NA                 Admin
5    Customer Service              Banking            Banking
6    Customer Service              NA                 NA
7    Economics                     Education          Education

Here's the code I've tried:

NewDf <- OldDf %>% 
  mutate(My_Category = "") %>%
  mutate(My_Category = ifelse(JobCategory_1 %in% NotSectors, JobCategory_2, JobCategory_1))

... which replaces the right values, but returns numbers instead of the correct char strings

Do you have any tips to do this most efficiently? I'd really appreciate your help!

Aucun commentaire:

Enregistrer un commentaire