R - 向数据框添加行索引,但处理最小等级的关联

时间:2015-06-27 15:13:42

标签: r data-manipulation

我在这个SO线程中成功使用了答案 r-how-to-add-row-index-to-a-data-frame-based-on-combination-of-factors但我需要处理可以绑定两个(或更多)行的情况。

df <- data.frame(
season = c(2014,2014,2014,2014,2014,2014, 2014, 2014), 
week = c(1,1,1,1,2,2,2,2), 
player.name = c("Matt Ryan","Peyton Manning","Cam Newton","Matthew Stafford","Carson Palmer","Andrew Luck", "Aaron Rodgers", "Chad Henne"), 
fant.pts.passing = c(28,19,29,28,18,22,29,22)
)

df <- df[order(-df$season, df$week, -df$fant.pts.passing),]

df$Index <- ave( 1:nrow(df), df$season, df$week, FUN=function(x) 1:length(x) )

df

在这个例子中,第1周,Matt Ryan和Matthew Stafford都是2,然后Peyton Manning将是4。

3 个答案:

答案 0 :(得分:4)

您希望在rank来电中使用ties.method="min"功能ave

df$Index <- ave(-df$fant.pts.passing, df$season, df$week,
                FUN=function(x) rank(x, ties.method="min"))
df
#   season week      player.name fant.pts.passing Index
# 3   2014    1       Cam Newton               29     1
# 1   2014    1        Matt Ryan               28     2
# 4   2014    1 Matthew Stafford               28     2
# 2   2014    1   Peyton Manning               19     4
# 7   2014    2    Aaron Rodgers               29     1
# 6   2014    2      Andrew Luck               22     2
# 8   2014    2       Chad Henne               22     2
# 5   2014    2    Carson Palmer               18     4

答案 1 :(得分:3)

假设您希望按季节和星期排名,可以使用dplyr的{​​{1}}轻松完成此操作:

min_rank

答案 2 :(得分:2)

您可以使用frank中较快的data.table并通过引用分配(:=)列

library(data.table)#v1.9.5+
setDT(df)[, indx := frank(-fant.pts.passing, ties.method='min'), .(season, week)]
 #   season week      player.name fant.pts.passing indx
 #1:   2014    1       Cam Newton               29    1
 #2:   2014    1        Matt Ryan               28    2
 #3:   2014    1 Matthew Stafford               28    2
 #4:   2014    1   Peyton Manning               19    4
 #5:   2014    2    Aaron Rodgers               29    1
 #6:   2014    2      Andrew Luck               22    2
 #7:   2014    2       Chad Henne               22    2
 #8:   2014    2    Carson Palmer               18    4