Home > front end >  Mapping vector of values to custom value
Mapping vector of values to custom value

Time:03-21

I have vector of values like some Job Positions lets say

JobPosition <- as.data.frame(rep(c("Helpdesk","Data Engineer","Salesman"), 5))

I want each Helpdesk associate with JobPosition 1, each DE with JobPosition2, each Salesman with JobPosition3. I know how to make them random strings using dplyr but not how to convert them into desired string with incremental number

Expected output

Job position    NewJobPosition
Helpdesk        JobPosition1
Data engineer   JobPosition2
Salesman        JobPosition3
Helpdesk        JobPosition1
Data engineer   JobPosition2
Salesman        JobPosition3

CodePudding user response:

We can do,

  JobPosition %>% mutate(number = as.integer(fct_inorder(Position))) %>% mutate(NewJobPosition = paste0('JobPosition', number)) %>% select(Position, NewJobPosition)

        Position NewJobPosition
1       Helpdesk   JobPosition1
2  Data Engineer   JobPosition2
3       Salesman   JobPosition3
4       Helpdesk   JobPosition1
5  Data Engineer   JobPosition2
6       Salesman   JobPosition3
7       Helpdesk   JobPosition1
8  Data Engineer   JobPosition2
9       Salesman   JobPosition3
10      Helpdesk   JobPosition1
11 Data Engineer   JobPosition2
12      Salesman   JobPosition3
13      Helpdesk   JobPosition1
14 Data Engineer   JobPosition2
15      Salesman   JobPosition3

Data

JobPosition <- data.frame('Position' = rep(c("Helpdesk","Data Engineer","Salesman"), 5))

CodePudding user response:

One way to do it (you can reduce code if you want, kept it like this for legibility)

library(dplyr)

JobPosition <- as.data.frame(rep(c("Helpdesk","Data Engineer","Salesman"), 5))
names(JobPosition) <- "Job Position"

#Give every unique Jobposition a seperate number
position_numbers <- unique(JobPosition) %>%
  mutate(NewJobDecision = paste0("JobPosition", row_number()))

#Merge them
merge(y = JobPosition, 
      x = position_numbers)
  •  Tags:  
  • r
  • Related