0

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!

akrun
  • 874,273
  • 37
  • 540
  • 662
jazz_learn
  • 113
  • 2
  • 6

1 Answers1

2

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.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks. the order I guess with decreasing=TRUE isn't doing it as cleanly as the -df$v. Now based on the values sorted, how would i put them into quartiles . None of the functions seem to have a place for a group variable to create unique quartiles based on a category. – jazz_learn Jan 07 '16 at 21:05
  • 1
    @jazz_learn It is bad practise to ask multiple questions in a single post. I answered your `order`ing problem. It is better to ask the quartile as a new question. – akrun Jan 07 '16 at 21:07