I have a dataset that includes a stage number and a machine number - a small portion is reproduced below. However, in actuality, the full dataset includes 38 stages and is over 1 million rows long.
stage <- c("Stg1", "Stg1","Stg1","Stg1","Stg1","Stg1","Stg1","Stg1","Stg1","Stg1","Stg1","Stg1", "Stg2", "Stg2", "Stg2","Stg2","Stg2","Stg2","Stg2","Stg2","Stg2","Stg2","Stg10","Stg10","Stg10")
machine <- c("132H", "132H","132H", "132H", "132H", "212H", "212H", "212H", "212H", "212H", "217H", "217H", "132H", "132H", "212H", "212H", "212H", "212H", "212H", "217H", "217H", "217H", "132H", "132H", "132H")
df <- data.frame(stage,machine)
head(df)
stage machine
1 Stg1 132H
2 Stg1 132H
3 Stg1 132H
4 Stg1 132H
5 Stg1 132H
6 Stg1 212H
My goal is to create a new column that will sequentially assign numbers to grouped stages and machines. Ultimately, the code that will produce an output like this:
Stage Machine JobStage
Stg1 132H 1
Stg1 132H 1
Stg1 132H 1
Stg1 132H 1
Stg1 132H 1
Stg1 212H 2
Stg1 212H 2
Stg1 212H 2
Stg1 212H 2
Stg1 212H 2
Stg1 217H 3
Stg1 217H 3
Stg2 132H 4
Stg2 132H 4
Stg2 212H 5
Stg2 212H 5
Stg2 212H 5
Stg2 212H 5
Stg2 212H 5
Stg2 217H 6
Stg2 217H 6
Stg2 217H 6
Stg10 132H 7
Stg10 132H 7
Stg10 132H 7
I am aware you can do something like this for each stage and each machine, but it is time consuming especially for a large dataset:
df$JobStage[df$stage == "Stg1" & df$machine == "132H"] <- 1
df$JobStage[df$stage == "Stg1" & df$machine == "212H"] <- 2
...
I was trying to use dplyr with group_by() and mutate(), but I am not sure how to capture the different stages and machines properly and assign it a number. I know that unique() doesn't work for character values, but maybe the code would be something like this:
df %>% group_by(stage, machine) %>% mutate(JobStage = unique(stage) & unique(machine))
Any help would be very appreciated. Thank you.