R-将行索引添加到数据框,但以最小等级处理关系 [英] R - Add row index to a data frame but handle ties with minimum rank

查看:30
本文介绍了R-将行索引添加到数据框,但以最小等级处理关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此SO线程中成功使用了答案 r-如何将行索引添加到基于因素组合的数据帧中,但我需要处理可以捆绑两行(或更多行)的情况.

I successfully used the answer in this SO thread r-how-to-add-row-index-to-a-data-frame-based-on-combination-of-factors but I need to handle situation where two (or more) rows can be tied.

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.

In this example, for week 1, Matt Ryan and Matthew Stafford would both be 2, and then Peyton Manning would be 4.

推荐答案

您可能希望将 rank 函数与 ties.method ="min" 一起使用,code> ave 调用:

You would want to use the rank function with ties.method="min" within your ave call:

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

这篇关于R-将行索引添加到数据框,但以最小等级处理关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆