[R] rank/sort problem

Axel Urbiz axel.urbiz at gmail.com
Sat Nov 21 13:44:13 CET 2015


I would like to sort the df below, such that it sorts y1 in decreasing order for tt == 1 and in increasing order for 
tt == 0. My solution is below, but curious if there might be something better (meaning faster in this case). 

Actually, if instead if implicitly sorting, I could add a variable ‘rank’ as in my ‘hope’ data frame below, that would work too (as I just need the ranking of observations, not necessarily the data explicitly sorted in the results).

### Sample data
y1 <- c(50,100,200,20,400,100,500,1000,12,25)
tt <- factor(c(1,1,1,0,0,0,0,1,0,0))
df <- data.frame(y1, tt)
### My solution
sorted <- rbind(df[df$tt == 1, ] %>% arrange(desc(y1)),
                df[df$tt == 0, ] %>% arrange(y1))
### What I hope to get
hope <- data.frame(df,
                   rank = c(4, 3, 2, 6, 9, 8, 10, 1, 5, 7))

Thanks for any help.

Best Axel.
	[[alternative HTML version deleted]]

More information about the R-help mailing list