I have this data frame
df <- data.frame(
Machine_ID= c(1,1,1,1,2,2,2,2,2,2,3,3,3),
Operation = c("Start", "Stop", "Start", "Stop", "Stop", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop", "Start"))
> df
Machine_ID Operation
1 1 Start
2 1 Stop
3 1 Start
4 1 Stop
5 2 Stop
6 2 Stop
7 2 Start
8 2 Stop
9 2 Start
10 2 Stop
11 3 Start
12 3 Stop
13 3 Start
And I would like to correct a sequence of operation. Every machine should have an even number of operation with combination of one Start and one End.
So I would like to have df like this
> df
Machine_ID Operation
1 1 Start
2 1 Stop
3 1 Start
4 1 Stop
5 2 Start
6 2 Stop
7 2 Start
8 2 Stop
9 2 Start
10 2 Stop
11 3 Start
12 3 Stop
13 3 Start
14 3 Stop
I tried make a loop with IF statements, but its not optimal solution for my databse.
CodePudding user response:
Machine_ID <- rep(1:4,each=4)
Operation <- rep(c("Start", "Stop"),8)
df<-cbind.data.frame(Machine_ID,Operation)
CodePudding user response:
Here is one way to generate an even number of rows for each machine id, if the sequence is of odd value then it adds one additional row
tmp=tapply(df$Operation,df$Machine_ID,length)
tmp=ceiling(tmp/2)*2
data.frame(
"Machine_ID"=rep(names(tmp),tmp),
"Operation"=c("Start","Stop")
)