user2363642
user2363642

Reputation: 757

sort by ID variable R

I have data as follows. I want to rev sort the column "presum" within each id.

Obs hai_dispense_number   pdc1 dayscov2   pdc2 Time ID gh sr pre presum
1    1  Patient HAI0000072 1.0000       30 1.0000   -2  1  0  0   1     -1
2    2  Patient HAI0000072 0.0667        1 0.0333   -1  2  0  0   1     -2
3    3  Patient HAI0000072 1.0000       29 0.9667    1  3  1  1   0      0
4    4  Patient HAI0000072 0.0000        0 0.0000    2  4  1  2   0      0
5    5  Patient HAI0000072 0.0000        0 0.0000    3  5  1  3   0      0
6    6  Patient HAI0000072 0.0000        0 0.0000    4  6  1  4   0      0
7    7  Patient HAI0000072 0.0000        0 0.0000    5  7  1  5   0      0
8    8  Patient HAI0000072 0.4667       14 0.4667    6  8  1  6   0      0
9    9  Patient HAI0000072 1.0000       30 1.0000    7  9  1  7   0      0
10  10  Patient HAI0000072 0.9333       29 0.9667    8 10  1  8   0      0
11  11  Patient HAI0000072 1.0000       30 1.0000    9 11  1  9   0      0
12  12  Patient HAI0000072 0.3333       11 0.3667   10 12  1 10   0      0
13  13  Patient HAI0000072 0.8333       30 1.0000   11 13  1 11   0      0
14  14  Patient HAI0000072 0.9667       29 0.9667   12 14  1 12   0      0
15  15  Patient HAI0000560 1.0000       30 1.0000   -6  1  0  0   1     -1
16  16  Patient HAI0000560 1.0000       29 0.9667   -5  2  0  0   1     -2
17  17  Patient HAI0000560 1.0000       29 0.9667   -4  3  0  0   1     -3
18  18  Patient HAI0000560 0.1000        3 0.1000   -3  4  0  0   1     -4
19  19  Patient HAI0000560 1.0000       30 1.0000   -2  5  0  0   1     -5
20  20  Patient HAI0000560 1.0000       29 0.9667   -1  6  0  0   1     -6
21  21  Patient HAI0000560 1.0000       30 1.0000    1  7  1  1   0      0
22  22  Patient HAI0000560 1.0000       29 0.9667    2  8  1  2   0      0
23  23  Patient HAI0000560 0.9667       29 0.9667    3  9  1  3   0      0
24  24  Patient HAI0000560 0.9667       28 0.9333    4 10  1  4   0      0
25  25  Patient HAI0000560 1.0000       30 1.0000    4 11  1  5   0      0
26  26  Patient HAI0000560 0.9667       28 0.9333    6 12  1  6   0      0
27  27  Patient HAI0000560 0.9667       28 0.9333    7 13  1  7   0      0
28  28  Patient HAI0000560 1.0000       30 1.0000    8 14  1  8   0      0

I have tried this, to avail:

y<-df[sort(df$hai_dispense_number, df$presum),] 

I know the difference between sort and order. I definitely want to sort here. I need the pdc2 values to retain their values in the order they are in. Just want to invert the presum variable.

Thank you in advance

Upvotes: 0

Views: 429

Answers (2)

vinchinzu
vinchinzu

Reputation: 614

Use the plyr package

library(plyr)

where df is your dataset

arrange(df, desc(presum))

Upvotes: 0

Metrics
Metrics

Reputation: 15458

library(plyr)
ddply(df,.(ID), transform,presum=sort(presum))

Upvotes: 2

Related Questions