如何在R中一次按两列排列行?

时间:2014-12-02 22:32:33

标签: r dataframe rank

以下是基于第v2列排名的代码:

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

但我真的想根据v2和/或v1进行排名,因为v2中存在联系。如果不使用RPostgreSQL,我怎么能这样做?

4 个答案:

答案 0 :(得分:2)

order可以使用,但是对于操作数据框,还可以查看plyrdplyr个包。

> arranged_x <- arrange(x, v2, v1)

答案 1 :(得分:1)

怎么样:

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 :(得分:0)

在这里,我们创建一个数字序列,然后将其重新排序,就好像它是在有序数据附近创建的一样:

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

或者:

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

甚至:

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

答案 3 :(得分:0)

尝试一下:

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