Reputation: 197
With the following data I would like to rearrange rows within each unique ProjectID.
Data <- data.frame(ProjectID=c(123,123,123,124,125,125,126,126,126,126,128,129),
Value=c(1,4,7,3,8,9,2,5,3,7,2,6),
Sequence=c(1,3,2,1,3,2,1,1,4,2,2,4))
Within each unique ProjectID, if the Sequence contains either "1,3,2" or "1,4,2" I want to reorder the rows to follow "3,1,2" or "4,1,2", respectively.
In ProjectID 126, there are four observations with Sequence 1,1,4,2, so the expected result should show 1,4,1,2.
How can I accomplish this?
Result should be as follows
Result <- data.frame(ProjectID=c(123,123,123,124,125,125,126,126,126,126,128,129),
Value=c(4,1,7,3,8,9,2,3,5,7,2,6),
Sequence=c(3,1,2,1,3,2,1,4,1,2,2,4))
Upvotes: 0
Views: 71
Reputation: 32548
do.call(rbind,
lapply(split(Data, Data$ProjectID), function(a){
if(identical(a$Sequence, c(1,4,2))){
a[match(a$Sequence, c(4,1,2)),]
}else if(identical(a$Sequence, c(1,3,2))){
a[match(a$Sequence, c(3,1,2)),]
}else{
a
}
}
)
)
# ProjectID Value Sequence
#123.2 123 4 3
#123.1 123 1 1
#123.3 123 7 2
#124 124 3 1
#125.5 125 8 3
#125.6 125 9 2
#126.8 126 5 4
#126.7 126 2 1
#126.9 126 7 2
#128 128 2 2
#129 129 6 4
Upvotes: 1