计算每个组的排名

use*_*502 6 r ranking plyr

我有df类型和价值观.我想按x内部顺序对它们进行排序,type并计算有多少其他行的行n数高于x(列pos).

例如

df <- data.frame(type = c("a","a","a","b","b","b"),x=c(1,77,1,34,1,8))
# for type a row 3 has a higher x than row 1 and 2 so has a pos value of 2
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

library(plyr)
df <- data.frame(type = c("a","a","a","b","b","b"),x=c(1,77,1,34,1,8))
df <- ddply(df,.(type), function(x) x[with(x, order(x)) ,])
df <- ddply(df,.(type), transform, pos = (seq_along(x)-1) )

     type  x pos
1    a  1   0
2    a  1   1
3    a 77   2
4    b  1   0
5    b  8   1
6    b 34   2
Run Code Online (Sandbox Code Playgroud)

但是这种方法没有考虑a第1行和第2行之间的关系.什么是最简单的方法来获得关系具有相同值的输出,例如

     type  x pos
 1    a  1   0
 2    a  1   0
 3    a 77   2
 4    b  1   0
 5    b  8   1
 6    b 34   2
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 8

ddply(df,.(type), transform, pos = rank(x,ties.method ="min")-1)

  type  x pos
1    a  1   0
2    a 77   2
3    a  1   0
4    b 34   2
5    b  1   0
6    b  8   1
Run Code Online (Sandbox Code Playgroud)