It was a little difficult for me to sort some rows in my data frame in R. The data has the following structure.
df <-
ID TIME DVID AMT DV PERIOD
1 0 0 50 NA 1
1 0.5 1 0 10 1
1 0.5 2 0 15 1
2 600 0 100 NA 2
2 600 1 0 2.5 2
2 600 2 0 4 2
2 602 1 0 20 2
2 602 2 0 35 2
3 800 0 50 NA 3
3 800 1 0 5 3
3 800 2 0 10 3
For PERIOD >= 2I want to change the lines for DVID to DVID 1, 2, then 0, as shown in the output frame below dfout. Data must be ordered by identifier, TIME, PERIOD.
I tried to use orderBy, but I could achieve my goal. An example of use orderByis this.
library(doBy)
dfout <- orderBy(~ID+TIME+PERIOD, data=df)
The output should be as follows:
dfout <-
ID TIME DVID AMT DV PERIOD
1 0 0 50 NA 1
1 0.5 1 0 10 1
1 0.5 2 0 15 1
2 600 1 0 2.5 2
2 600 2 0 4 2
2 600 0 100 NA 2
2 602 1 0 20 2
2 602 2 0 35 2
3 800 1 0 5 3
3 800 2 0 10 3
3 800 0 50 NA 3
I would appreciate if anyone would share a trick on how to do this in R.
source
share