Reputation: 113
I have a data frame that I created as a sample
v<-data.frame( g= c(sample(1:10, 8)))
g<-data.frame( v= c(1,1,1,1,2,2,2,2))
df<-cbind(g,v)
df_s <-df[order(df$g,df$v,decreasing=TRUE),]
The g column is a group of common values, lets say dates. I want to sort per each g the values in descending order and then put them into quintiles or really n-tiles.
I had the code
df_s <-df[order(df$g,df$v,decreasing=TRUE),]
to sort it but the output is not coming in order expected, see below. I want
1,v high
1,v mid
1,v low
2,v high
2,v mid
2, v low
Instead I get this.
v g
8 2 10
2 1 9
5 2 8
3 1 6
7 2 5
4 1 4
6 2 2
1 1 1
Any help is appreciated. Thanks!
Upvotes: 0
Views: 47
Reputation: 887108
We can try
df[order(df$v, -df$g),]
In the OP's code, by using decreasing=TRUE
, it gives a different order
order(df$g,df$v,decreasing=TRUE)
#[1] 3 5 2 6 1 4 7 8
order(df$g,-df$v)
#[1] 8 7 4 1 6 2 5 3
It would have been better to use set.seed
to make the example reproducible.
Upvotes: 2