下面是排名基於列V2代碼:如何在R中一次對兩列進行排名?
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?
下面是排名基於列V2代碼:如何在R中一次對兩列進行排名?
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?
如何:
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
order
作品,但對於操縱數據幀,還檢查出plyr
和dplyr
包。
> arranged_x <- arrange(x, v2, v1)
這裏我們創建了一個數字序列,然後重新排序,如果它是附近的有序數據發佈:
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)))
首先,'tie.method'不是必需的,'order'不會有關係。其次,這個數據失敗:'x < - data.frame(v1 = c(2,3,1,2,1),v2 = c(1,1,3,2,1))',所以它是錯了。 – user 2017-05-12 05:07:51