gpt4 book ai didi

R - 将行索引添加到数据框但处理具有最低等级的关系

转载 作者:行者123 更新时间:2023-12-04 10:56:21 24 4
gpt4 key购买 nike

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

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 岁。

最佳答案

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

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 - 将行索引添加到数据框但处理具有最低等级的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com