How to rank rows by two columns at once in R?

Here is the code for ranking based on v2 column:

x <- data.frame(v1 = c(2,1,1,2), v2 = c(1,1,3,2)) x$rank1 <- rank(x$v2, ties.method='first') 

But I really want to rank based on both v2 and v1, since there are connections in v2. How can I do this without using RPostgreSQL?

+6
source share
4 answers

What about:

 within(x, rank2 <- rank(order(v2, v1), ties.method='first')) # v1 v2 rank1 rank2 # 1 2 1 1 2 # 2 1 1 2 1 # 3 1 3 4 4 # 4 2 2 3 3 
+2
source

order works, but check the plyr and dplyr packages to manage data frames.

 > arranged_x <- arrange(x, v2, v1) 
+3
source

Here we create a sequence of numbers and then reorder them as if they were created near the ordered data:

 x$rank <- seq.int(nrow(x))[match(rownames(x),rownames(x[order(x$v2,x$v1),]))] 

Or:

 x$rank <- (1:nrow(x))[order(order(x$v2,x$v1))] 

Or even:

 x$rank <- rank(order(order(x$v2,x$v1))) 
0
source

Try it:

 x <- data.frame(v1 = c(2,1,1,2), v2 = c(1,1,3,2)) # The order function returns the index (address) of the desired order # of the examined object rows orderlist<- order(x$v2, x$v1) # So to get the position of each row in the index, you can do a grep x$rank<-sapply(1:nrow(x), function(x) grep(paste0("^",x,"$"), orderlist ) ) x # For a little bit more general case # With one tie x <- data.frame(v1 = c(2,1,1,2,2), v2 = c(1,1,3,2,2)) x$rankv2<-rank(x$v2) x$rankv1<-rank(x$v1) orderlist<- order(x$rankv2, x$rankv1) orderlist #This rank would not be appropriate x$rank<-sapply(1:nrow(x), function(x) grep(paste0("^",x,"$"), orderlist ) ) #there are ties grep(T,duplicated(x$rankv2,x$rankv1) ) # Example for only one tie makeTieRank<-mean(x[which(x[,"rankv2"] %in% x[grep(T,duplicated(x$rankv2,x$rankv1) ),][,c("rankv2")] & x[,"rankv1"] %in% x[grep(T,duplicated(x$rankv2,x$rankv1) ),][,c("rankv1")]),]$rank) x[which(x[,"rankv2"] %in% x[grep(T,duplicated(x$rankv2,x$rankv1) ),][,c("rankv2")] & x[,"rankv1"] %in% x[grep(T,duplicated(x$rankv2,x$rankv1) ),][,c("rankv1")]),]$rank<-makeTieRank x 
0
source

Source: https://habr.com/ru/post/1208194/


All Articles